题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
return isBalanced(root)[0] == 1;
if(root == null){
return new int[]{1,0};
}
int[] left = isBalanced(root.left);
int[] right = isBalanced(root.right);
if(left[0]==1 && right[0] == 1 && Math.abs(left[1]-right[1])<=1){
return new int[]{1,Math.max(left[1],right[1])+1};
}
return new int[]{0,0};
}
}
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
return isBalanced(root)[0] == 1;
}
//后序遍历
public int[] isBalanced(TreeNode root){if(root == null){
return new int[]{1,0};
}
int[] left = isBalanced(root.left);
int[] right = isBalanced(root.right);
if(left[0]==1 && right[0] == 1 && Math.abs(left[1]-right[1])<=1){
return new int[]{1,Math.max(left[1],right[1])+1};
}
return new int[]{0,0};
}
}
查看8道真题和解析