【发布时间】:2020-12-15 09:39:25
【问题描述】:
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int rightCount = maxDepth(root.right);
int leftCount = maxDepth(root.left);
if(Math.abs(rightCount-leftCount)<=1) return true;
return false;
}
public int maxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
检查两个分支的最大深度并确定绝对值是否为
【问题讨论】:
-
视情况而定。你认为一棵有两条长的、线性的左右臂的树是平衡的吗?它们将具有相同的深度,但树不会很满,因此对这棵树的操作往往是线性的而不是对数的。本质上是一棵像
1 <- 2 <- 3 <- 4 <- 5 (root) -> 6 -> 7 -> 8 -> 9这样的树。根的左右分支的深度相同(4),但是这棵树是否平衡?
标签: data-structures tree binary-tree