您的位置:首页 > 其它

LeetCode Balanced Binary Tree

2015-09-05 00:44 267 查看
原题链接在这里: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: