美文网首页
110. Balanced Binary Tree

110. Balanced Binary Tree

作者: lqsss | 来源:发表于2018-02-23 22:17 被阅读0次

    题目

    Given a binary tree, determine if it is height-balanced.
    
    For this problem, a height-balanced binary tree is defined as:
    
    a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
    
    Example 1:
    
    Given the following tree [3,9,20,null,null,15,7]:
    
        3
       / \
      9  20
        /  \
       15   7
    Return true.
    
    Example 2:
    
    Given the following tree [1,2,2,3,3,null,null,4,4]:
    
           1
          / \
         2   2
        / \
       3   3
      / \
     4   4
    Return false.
    
    

    思路:

    1. 所谓平衡二叉树,如果每个节点的左右两子树深度差绝对值不超过1;
    2. 递归;以一个最普通的二叉树思考,该节点的|左子树深度 -左子树深度|<=1,且它的左子树和右子树也满足-->递归
    3. 如何获取该节点的深度,这里又是另外一个递归,以一个最普通的二叉树思考:
      leftHight >= rightHight ? leftHight + 1 : rightHight + 1;

    代码

    public class BalancedBinaryTree {
        public boolean isBalanced(TreeNode root) {
            if(root!=null){
                int leftHight = TreeDepth(root.left);
                int rightHight = TreeDepth(root.right);
                if(leftHight -rightHight < - 1 || leftHight -rightHight >1){
                    return false;
                }
                return isBalanced(root.left) && isBalanced(root.right);
            }
            return true;
        }
    
        public int TreeDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftHight = TreeDepth(root.left);
            int rightHight = TreeDepth(root.right);
            return leftHight >= rightHight ? leftHight + 1 : rightHight + 1;
        }
    }
    

    相关文章

      网友评论

          本文标题:110. Balanced Binary Tree

          本文链接:https://www.haomeiwen.com/subject/unrfxftx.html