簡直off: 平衡二叉樹
阿新 • • 發佈:2018-12-24
文章目錄
前言
最近有道雲筆記老是沒響應,會員也這樣,所以把演算法的筆記公開到這個csdn,也算是公開的鞭策。
題目常練習起點位置: https://www.nowcoder.com/ta/coding-interviews?asc=false&order=knowledgePoint
題目
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
思路
什麼是平衡的二叉樹
子樹高度差不超過1
暴力揭發
中序遍歷,重複地,低效地計算每個訪問到的node ,算這個node 的左右子樹的高度
public class Solution {
boolean isBalance = true;
public boolean IsBalanced_Solution(TreeNode root) {
inorder(root);
return isBalance;
}
boolean inorder(TreeNode root) {
if (root == null);
else {
inorder(root.left);
if ( Math.abs(maxDepth(root.left) - maxDepth(root.right)) > 1){ isBalance = false; return false;}// is not balance
inorder(root.right);
}
return true;
}
int maxDepth(TreeNode root) {
if (root == null) return 0;
else return 1+ Math.max(maxDepth(root. left), maxDepth(root.right));
}
}
恭喜你通過本題
執行時間:24ms
佔用記憶體:9516k
優化,從下往上的
public class Solution {
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(left - right) > 1 ? -1 : 1 + Math.max(left, right);
}
}