您的位置:首页 > 其它

Balanced Binary Tree

2015-06-06 15:53 387 查看
Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

思路:对于每一个结点先求出左子树的高度和右子树的高度,然后判断它们的高度差,如果高度相差大于1则不是平衡二叉树,如果小于1,继续判断它的左子树和右子树是不是平衡二叉树。

/**
* 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) {
if(root==null) return true;
int left=sub_height(root.left);
int right=sub_height(root.right);
int diff=Math.abs(left-right);
if(diff>1) return false;
else return  isBalanced(root.left) && isBalanced(root.right);
}
public int sub_height(TreeNode subTree)
{
if(subTree==null) return 0;
if(subTree.left==null && subTree.right==null) return 1;
if(subTree.left==null) return sub_height(subTree.right)+1;
if(subTree.right==null) return sub_height(subTree.left)+1;
return Math.max(sub_height(subTree.right),sub_height(subTree.left))+1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: