LeetCode 110 Balanced Binary Tree
===================
方法一:
平衡二叉樹(shù)的判定,一般來(lái)說(shuō)可以在TreeNode數(shù)據(jù)結(jié)構(gòu)中增加一個(gè)depth表示以該節(jié)點(diǎn)為根節(jié)點(diǎn)的子樹(shù)的深度,從而利用左右兒子節(jié)點(diǎn)子樹(shù)深度的差值做判斷。
注意這里的depth是子樹(shù)的深度,而不是節(jié)點(diǎn)的深度,這兩者是相反的。
這里由于無(wú)法修改數(shù)據(jù)結(jié)構(gòu),在每次判斷子樹(shù)深度時(shí)都調(diào)用一次dfs求取。不知道是否有更好的辦法。
代碼中的細(xì)節(jié):
利用dfs實(shí)現(xiàn)子樹(shù)深度的求取 ,父節(jié)點(diǎn)的depth為左右兒子節(jié)點(diǎn)max值+1。
public int dfs(TreeNode root) {
if (root == null) return 0;
else {
int h1 = dfs(root.left) + 1;
int h2 = dfs(root.right) + 1;
return (h1 > h2) ? h1 : h2;
}
}
注意遞歸的終止條件為root==null,若在該節(jié)點(diǎn)處左右子樹(shù)平衡,則分別遞歸搜索左右子樹(shù)是否平衡。
if (root == null) return true;
else {
int h1 = dfs(root.left);
int h2 = dfs(root.right);
if (h1 - h2 > 1 || h1 - h2 < -1) {
return false;
} else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
具體代碼如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
else {
int h1 = dfs(root.left);
int h2 = dfs(root.right);
if (h1 - h2 > 1 || h1 - h2 < -1) {
return false;
} else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
}
public int dfs(TreeNode root) {
if (root == null) return 0;
else {
int h1 = dfs(root.left) + 1;
int h2 = dfs(root.right) + 1;
return (h1 > h2) ? h1 : h2;
}
}
}
方法二:
之前糾結(jié)了很久,因?yàn)榉椒ㄒ环Ndfs求height被反復(fù)調(diào)用,實(shí)際上一次dfs就可以判斷子樹(shù)是否平衡,那到底怎么在dfs中既返回depth又返回布爾型的是否平衡呢?
網(wǎng)上找到了一個(gè)很好的思路,用return -1代表不平衡,從而解決了int與boolean返回值無(wú)法同時(shí)返回的問(wèn)題。
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
// If root is unbalanced, then getDepth will return -1; else, getDepth will return max depth
else return (getDepth(root) != -1);
}
public int getDepth(TreeNode root) {
if (root == null) return 0;
else {
int ld = getDepth(root.left);
int rd = getDepth(root.right);
if (ld == -1 || rd == -1 || Math.abs(ld - rd) > 1)
return -1;
else
return Math.max(ld,rd) + 1;
}
}
}