题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
代码实现
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
int diff = left - right;
if (diff != 0 && diff != 1 && diff != -1)
return false;
else{
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
}
public int TreeDepth(TreeNode root){
if(root == null)
return 0;
else{
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left,right)+1 ;
}
}
}
本文介绍了一种判断二叉树是否为平衡二叉树的方法。通过递归计算每个节点的左右子树深度,并比较差值来确定是否平衡。
14万+

被折叠的 条评论
为什么被折叠?



