题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
思路
直接边遍历边判断就OK了噢, dfs用于获取左右深度.
代码
public class Solution {
boolean ans = true;
int dfs(TreeNode node) {
if (node == null) return 0;
int l = dfs(node.left);
int r = dfs(node.right);
ans = ans && Math.abs(l - r) <= 1;
return Math.max(l, r) + 1;
}
public boolean IsBalanced_Solution(TreeNode root) {
dfs(root);
return ans;
}
}