当前位置:网站首页>[leetcode] 93 balanced binary tree

[leetcode] 93 balanced binary tree

2020-11-10 01:15:16 JaneRoad

subject :

image-20201110003015387

image-20201110003000050

Their thinking :

Bottom up recursion

Similar to post order traversal , For the node currently traversed , First, recursively judge whether the left and right subtrees are balanced , Then judge whether the subtree with the current node as the root is balanced . If a subtree is balanced , Then return to its height ( The height must be a nonnegative integer ), Otherwise return to -1−1. If there is a subtree imbalance , Then the whole binary tree must be unbalanced .

https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/

Code :

class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

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

版权声明
本文为[JaneRoad]所创,转载请带上原文链接,感谢