Balanced Binary Tree Leetcode

Posted 璨璨要好好学习

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Balanced Binary Tree Leetcode相关的知识,希望对你有一定的参考价值。

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.

 

这道题一开始的做法比较简单粗暴。
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left = isBalanced(root.left);
        boolean right = isBalanced(root.right);
        int l = depth(root.left);
        int r = depth(root.right);
        return Math.abs(l - r) <= 1 && left && right;
    }
    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        return Math.max(left, right) + 1;
    }
}

这样的话,每个节点都要求一次depth,depth的时间复杂度是O(n),所以总共的时间复杂度是O(n^2)。

可以采取自下而上(bottom up)的方法。这样的话,时间复杂度是O(n)。需要注意的是,只要左右有一个是-1,可以直接返回-1。不然的话可能出现两个子树的深度相同,但他们并不是平衡的。

public class Solution {
    public boolean isBalanced(TreeNode root) {
        return depthDif(root) != -1;
    }
    public int depthDif(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = depthDif(root.left);
        if (left == -1) {
            return -1;
        }
        int right = depthDif(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
    }
}

 

以上是关于Balanced Binary Tree Leetcode的主要内容,如果未能解决你的问题,请参考以下文章

LC.110. Balanced Binary Tree

Leetcode[110]-Balanced Binary Tree

110. Balanced Binary Tree

110. Balanced Binary Tree

Leet-code144. Binary Tree Preorder Traversal

LeetCode-Easy刷题(24) Balanced Binary Tree