平衡树
二叉树的深度
http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b
public class Solution {
boolean flag = true;
public boolean IsBalanced_Solution(TreeNode root) {
Tree(root);
return flag;
}
//遍历比较左右树是否平衡
public void Tree(TreeNode root) {
if (root == null) {
return;
}
if (Math.abs(TreeDepth(root.left) - TreeDepth(root.right)) > 1) {
flag = false;
}
Tree(root.left);
Tree(root.right);
}
//树深
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
return 1
Math.max(TreeDepth(root.left), TreeDepth(root.right));
}
}
}根据定义来做最好理解,也好写些,是否平衡就是比较所有左右树深度差的绝对值是否小于等于1,不是就不是平衡树,然后就两个一个遍历一个树的深度结合过一遍就行。直译定义来写就可以,不然按自己思路写会容易忘记解法。


小天才公司福利 1316人发布