题解 | #平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
if (Math.abs(checkBalanceTree(root.left)-checkBalanceTree(root.right)) > 1) {
return false;
}
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int checkBalanceTree(TreeNode root) {
if (root == null) {
return 0;
}
int leftHight = checkBalanceTree(root.left)+1;
int rightHight = checkBalanceTree(root.right)+1;
return Math.max(leftHight,rightHight);
}
} 求出左子树的最大高度,求出右子树的最大高度,判断是否是平衡二叉树。
查看1道真题和解析