原题链接在这里:https://leetcode.com/problems/balanced-binary-tree/
用递归方法求最大深度,如果左右最大深度相差大于一,则返回-1,若是已有左或者右的返回值为-1,则立即返回-1.
最后看返回到root时是否为一个负数,若是负数则不是balanced,若是正数,则返回了最大深度,是balanced.
最大深度可参见Maximum Depth of Binary Tree.
AC Java:
/**
* 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) {
return maxDepth(root) >= 0;
}
private int maxDepth(TreeNode root){
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
if(left < 0 || right < 0 || Math.abs(left - right) > 1){
return -1;
}
return Math.max(left,right)+1;
}
}