首页 > 其他 > 详细

leetcode--Balanced Binary Tree

时间:2014-01-29 13:59:55      阅读:346      评论:0      收藏:0      [点我收藏+]

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.

 

bubuko.com,布布扣
 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isBalanced(TreeNode root){
12        boolean isBalanced = true;
13         if(root != null){
14             if(heightOfTree(root.left) > heightOfTree(root.right) + 1 || 
15                  heightOfTree(root.left) < heightOfTree(root.right) - 1)
16                  isBalanced = false;
17             else
18                  isBalanced = isBalanced(root.left) && isBalanced(root.right);
19         }
20         return isBalanced;
21     }
22     
23     public int heightOfTree(TreeNode root){
24         int height = 0;
25         if(root != null)
26             height = 1 + Math.max(heightOfTree(root.left), heightOfTree(root.right));
27         return height;
28     }    
29 }
bubuko.com,布布扣

leetcode--Balanced Binary Tree

原文:http://www.cnblogs.com/averillzheng/p/3535949.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!