LeetCode: Balanced Binary Tree 解题报告

时间:2021-07-09 08:26:16

Balanced Binary Tree

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.

Show Tags
LeetCode: Balanced Binary Tree  解题报告

SOLUTION 1:

使用inner Class来解决

 // Solution 1:
public boolean isBalanced1(TreeNode root) {
return dfs(root).isBalanced;
} // bug 1: inner class is like: "public class ReturnType {", no ()
public class ReturnType {
boolean isBalanced;
int depth; ReturnType(int depth, boolean isBalanced) {
this.depth = depth;
this.isBalanced = isBalanced;
}
} public ReturnType dfs(TreeNode root) {
ReturnType ret = new ReturnType(0, true); if (root == null) {
return ret;
} ReturnType left = dfs(root.left);
ReturnType right = dfs(root.right); ret.isBalanced = left.isBalanced
&& right.isBalanced
&& Math.abs(left.depth - right.depth) <= 1; // bug 2: remember to add 1( the root depth )
ret.depth = Math.max(left.depth, right.depth) + 1; return ret;
}

SOLUTION 2:

将 get depth函数提出

 // Solution 2:
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} return isBalanced(root.left) && isBalanced(root.right)
&& Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1;
} public int getDepth(TreeNode root) {
if (root == null) {
return 0;
} return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
}

SOLUTION 3:

leetcode又加强了数据,solution 2对于一条单链过不了了。所以主页君加了一点优化,当检测到某个子节点为null时,求另一个子树的depth时,及时退出,这

样就不会产生getdepth太深的问题:

 // Solution 2:
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} boolean cut = false;
if (root.right == null || root.left == null) {
cut = true;
} return isBalanced(root.left) && isBalanced(root.right)
&& Math.abs(getDepth(root.left, cut) - getDepth(root.right, cut)) <= ;
} public int getDepth(TreeNode root, boolean cut) {
if (root == null) {
return -;
} if (cut && (root.left != null || root.right != null)) {
// if another tree is not deep, just cut and return fast.
// Improve the performance.
return ;
} return + Math.max(getDepth(root.left, false), getDepth(root.right, false));
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/IsBalanced.java