题目: 平衡二叉树
思路: dfs
深搜递归函数返回深度,判断左右子树的深度差是否大于1。
代码:
public class Solution {
public boolean result = true;
public boolean IsBalanced_Solution(TreeNode root) {
dfs(root);
return result;
}
public int dfs (TreeNode root) {
if (root == null) {
return 0;
}
int l = dfs(root.left) + 1;
int r = dfs(root.right) + 1;
if (Math.abs(l - r) > 1) {
result = false;
}
return Math.max(l, r);
}
}