可以在调用链回归时进行比较以避免重复计算深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
boolean balanced=true;
public boolean isBalanced(TreeNode root) {
balanceHelper(root);
return balanced;
}
private int balanceHelper(TreeNode root)
{
if(root==null) return 0;
int right = balanceHelper(root.right);
int left = balanceHelper(root.left);
if(Math.abs(right-left)>1)
balanced=false;
return left>right?left+1:right+1;
}
}
网友评论