基于树的深度来判断平衡二叉树
平衡二叉树
http://www.nowcoder.com/questionTerminal/8b3b95850edb4115918ecebdf1b4d222
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.abs(left - right) <= 1;
}
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(right, left) + 1;
}
}
查看2道真题和解析