美文网首页
110. Balanced Binary Tree

110. Balanced Binary Tree

作者: 7ccc099f4608 | 来源:发表于2020-03-16 13:40 被阅读0次

https://leetcode-cn.com/problems/balanced-binary-tree/

image.png

(图片来源https://leetcode-cn.com/problems/balanced-binary-tree/

日期 是否一次通过 comment
2020-03-15 0

递归

public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        
        return helper(root) != -1;
    }
    
    private int helper(TreeNode root) {
        if(root == null) {
            return 0;
        }
        
        int leftD = helper(root.left);
        int rightD = helper(root.right);
        if(leftD == -1 || rightD == -1 || Math.abs(leftD-rightD) > 1) {
            return -1;
        }
        
        return Math.max(leftD, rightD) + 1;
    }

相关文章

网友评论

      本文标题:110. Balanced Binary Tree

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