劍指offer程式設計題(JAVA實現)——第39題:平衡二叉樹
阿新 • • 發佈:2018-12-27
github | https://github.com/JasonZhangCauc/JZOffer |
---|
- 劍指offer程式設計題(JAVA實現)——第39題:平衡二叉樹
- 題目描述
- 輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
public class Test39 {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) {
return true;
}
return (Math.abs(isDepth(root.left) - isDepth(root.right)) <= 1) && IsBalanced_Solution(root.left)
&& IsBalanced_Solution(root.right);
}
public int isDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(isDepth(root.left), isDepth(root.right));
}
}
//上面的做法有很明顯的問題,在判斷上層結點的時候,會多次重複遍歷下層結點,增加了不必要的開銷。
//如果改為從下往上遍歷,如果子樹是平衡二叉樹,則返回子樹的高度;
//如果發現子樹不是平衡二叉樹,則直接停止遍歷,這樣至多隻對每個結點訪問一次。
//其他做法
/**
public boolean IsBalanced_Solution(TreeNode root) {
return getDepth(root) != -1;
}
private int getDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = getDepth(root.left);
if (left == -1)
return -1;
int right = getDepth(root.right);
if (right == -1)
return -1;
return Math.abs(right - left) > 1 ? -1 : 1+Math.max(left, right);
}
*/