Balanced Binary Tree 平衡二叉树

Balanced Binary Tree 平衡二叉树

给一个二叉树,判断是否为平衡二叉树。

平衡二叉树:一个二叉树*每个节点* 的左右两个子树的高度差的绝对值不超过 1

img

Input: root = [3,9,20,null,null,15,7]
Output: true

img

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

思路

getHeight做递归 返回值小于0,说明不是平衡二叉树,边界条件节点无左右子树,返回0。

左右子树深度差大于1时,说明不是平衡二叉树, 返回-2。

public int getHeight(TreeNode root){
    
    
        if(root == null){
    
    
            return 0;
        }
        int l = getHeight(root.left);
        int r = getHeight(root.right);
        if(l<0||r<0){
    
    
            return -2;
        }
        if(Math.abs(l-r)>1){
    
    
            return -2;
        }
        return Math.max(l,r)+1;
    }

    public boolean isBalanced(TreeNode root) {
    
    
        return getHeight(root)>=0;        
    }

Tag

tree recursion

Guess you like

Origin blog.csdn.net/edisonzhi/article/details/115757633