题解 | #平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
二叉树的深度是从根节点开始(其深度为1)自顶向下逐层累加的;而二叉树高度是从叶节点开始(其高度为1)自底向上逐层累加的。虽然树的深度和高度一样,但是具体到树的某个节点,其深度和高度是不一样的。
public class Solution {
public boolean isBalance = true;
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
treeDeep(root);
return isBalance;
}
public int treeDeep (TreeNode root) {
if (root == null || !isBalance) {
return 0;
}
int left = treeDeep(root.left);
int right= treeDeep(root.right);
int heightMinus = Math.abs(left - right);
if (heightMinus <= 1) {
isBalance = true;
} else {
isBalance = false;
}
return Math.max(treeDeep(root.left), treeDeep(root.right)) + 1;
}
}
巨人网络成长空间 53人发布
查看22道真题和解析