您的位置:首页 > 其它

Balanced Binary Tree

2013-04-21 20:03 309 查看
/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null)return true;
return valid(root);
}
private boolean valid(TreeNode root){
if(root==null)return true;
int leftdep = height(root.left);
int rightdep = height(root.right);
boolean c = (leftdep-rightdep<=1&&leftdep-rightdep>=-1);
return c&&valid(root.left)&&valid(root.right);
}
private int height(TreeNode root){
if(root==null)return 0;
if(root.left==null&&root.right==null) return 1;
if(root.left==null)return height(root.right)+1;
if(root.right==null)return height(root.left)+1;
return Math.max(height(root.left),height(root.right))+1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  迭代