[leetCode]110.平衡二叉树

在这里插入图片描述

递归 自顶向下

需要重复计算子树的高度

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null)return true;
        int sub = Math.abs(treeHeight(root.left) - treeHeight(root.right));
        if(sub <= 1){
            return isBalanced(root.left) && isBalanced(root.right);
        }else{
            return false;
        }
    }

    public int treeHeight(TreeNode root){
        if(root == null){
            return 0;
        }else{
            int leftHeight = treeHeight(root.left);
            int rightHeight = treeHeight(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}

递归 自底向上

每个结点只需计算一次高度

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
final class TreeInfo{
    public int height;
    public boolean balanced;

    public TreeInfo(int h, boolean b){
        height = h;
        balanced = b;
    }
}

class Solution {
    public boolean isBalanced(TreeNode root) {
        return helper(root).balanced;
    }

    public TreeInfo helper(TreeNode root){
        if(root == null) return new TreeInfo(0,true);//空树大小为0

        TreeInfo left = helper(root.left);
        if(!left.balanced) return new TreeInfo(0,false);

        TreeInfo right = helper(root.right);
        if(!right.balanced) return new TreeInfo(0,false);

        if(Math.abs(left.height - right.height) < 2)return new TreeInfo(Math.max(left.height,right.height)+1,true);
        return new TreeInfo(0,false);
    }
}
posted @ 2020-07-08 10:20  消灭猕猴桃  阅读(54)  评论(0编辑  收藏  举报