平衡二叉树
描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
代码 (Java)
public class Solution {
private boolean IsBalanced = false;
public boolean IsBalanced_Solution(TreeNode root) {
TreeDepth(root);
return IsBalanced;
}
public int TreeDepth(TreeNode root) {
if (root == null) {
IsBalanced = true;
return 0;
}
int nLeft = TreeDepth(root.left);
int nRight = TreeDepth(root.right);
IsBalanced = Math.abs(nLeft - nRight) <= 1;
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
}
思路
- 类似于求 二叉树的深度,后序遍历,每求得一次左右子树的高度则判断一次是否平衡。