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;
if(Math.abs(getDepth(root.left) - getDepth(root.right)) < 2) {
return isBalanced(root.left) && isBalanced(root.right);
} else return false;
}
public int getDepth(TreeNode node) {
if(node == null) return 0;
int left = getDepth(node.left);
int right = getDepth(node.right);
return Math.max(left, right) + 1;
}
}
第二种递归解法
创建一个方法,参数是当前结点深度,返回值是左右节点所能到的深度。相比较上一个算法不会有重复搜索的情况,所以耗时较少。代码如下:
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
return judge(root, 0) > -1;
}
public int judge(TreeNode node, int depth) {
if(node == null) {
return depth - 1;
}
int left = judge(node.left, depth + 1);
int right = judge(node.right, depth + 1);
if(left != -1 && right != -1 && Math.abs(left - right) < 2) {
return Math.max(left, right);
} else {
return -1;
}
}
}
同时分享一个和我这个解法思路相同,但是更加清晰简洁的代码写法。链接:
Java solution based on height, check left and right node in every recursion to avoid further useless search