题目:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
知识点:
二叉树的深度。
思路:
对二叉树的深度进行遍历,若左右子树深度差2,就不是平衡二叉树。
答案:
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){return true;}
int leftCount = TreeDepth(root.left);
int rightCount = TreeDepth(root.right);
if(leftCount>rightCount+1 || leftCount+1<rightCount){//左右子树深度差
return false;
}else{
return true;
}
}
public int TreeDepth(TreeNode root) {//节点的深度遍历
if(root == null){return 0;}
int leftCount = TreeDepth(root.left);
int rightCount = TreeDepth(root.right);
return leftCount>rightCount?leftCount+1:rightCount+1;
}
}