题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路解析:
- 平衡二叉树:左右子树的深度不超过1
- 此题需要定义定义一个类,这样depth才不会因为作用域和作用范围的问题传不过去啊。
- 左右子树的差都要小于1。
代码:
public class Solution {
class Deepth{
int val=0;
}
public boolean IsBalanced_Solution(TreeNode root) {
Deepth depth=new Deepth();
return isBalanced(root,depth);
}
public boolean isBalanced(TreeNode root,Deepth d){
if(root ==null){
d.val =0;
return true;
}
Deepth left =new Deepth();
Deepth right = new Deepth();
if(isBalanced(root.left,left)&&isBalanced(root.right,right)){
int diff = left.val-right.val;
if(diff<=1 && diff >=-1){
d.val = right.val>left.val ? right.val+1 : left.val+1;
return true;
}
}
return false;
}
}