码迷,mamicode.com
首页 > 编程语言 > 详细

110. Balanced Binary Tree Java Solutions

时间:2016-05-01 19:11:12      阅读:171      评论: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.

Subscribe to see which companies asked this question

 1 /**
 2  * Definition for a binary tree node.
 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         return height(root) != -1;
13     }
14     
15     public int height(TreeNode t){
16         if(t == null) return 0; //到叶子节点再往下的情况
17         int lheight = height(t.left);
18         int rheight = height(t.right);
19         if(lheight == -1 || rheight == -1 || Math.abs(lheight-rheight) > 1){
20             return -1;//使用-1 标记左右子树高度相差大于1的情况
21         }
22         return 1 + Math.max(lheight,rheight);
23     }
24 }

 

110. Balanced Binary Tree Java Solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5450843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!