平衡二叉樹
描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
代碼 (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);
}
}
思路
- 類似於求 二叉樹的深度,後序遍歷,每求得一次左右子樹的高度則判斷一次是否平衡。