题解 | #平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
查看每个树的深度,相差2返回false,相差小于等于1,没有差2的返回true
import java.util.*;
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
Queue<TreeNode> we = new LinkedList<TreeNode>();
we.offer(root);
TreeNode p1;
TreeNode p2;
int n,p;
while(!we.isEmpty()){
p1 = we.poll();
n = deep(p1.left);
p = deep(p1.right);
if(n-p==2 || p-n==2){
return false;
}
if(p1.left != null){
we.offer(p1.left);
}
if(p1.right != null){
we.offer(p1.right);
}
}
return true;
}
public int deep(TreeNode root){
if(root == null){
return 0;
}
return (deep(root.left)+1) > (deep(root.right)+1) ? (deep(root.left)+1) : (deep(root.right)+1);
}
}