码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ - Balanced Binary Tree

时间:2014-05-05 09:54:44      阅读:378      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

判断树是否是平衡的,这道题中的平衡的概念是指任意节点的两个子树的高度相差不超过1,我用递归的方法把所有的节点的高度都计算了下,并且在计算的过程记录每个节点左右两颗子树的高度差,最后通过遍历这个高度差就可以知道是否是平衡的。

下面是AC代码:

bubuko.com,布布扣
 1  /**
 2      * Given a binary tree, determine if it is height-balanced.
 3      * For this problem, a height-balanced binary tree is defined as a binary tree 
 4      * in which the depth of the two subtrees of every node never differ by more than 1.
 5      * @param root
 6      * @return
 7      */
 8     public boolean isBalanced(TreeNode root){
 9         ArrayList<Integer> hd = new ArrayList<Integer>();
10         heightRec(root, hd);
11         for(int i: hd)
12             if(i>1)
13                 return false;
14         return true;
15     }
16     /**
17      * 
18      * @param root
19      * @param difference is for recording the difference of the height between the two subtrees
20      * @return
21      */
22     private int heightRec(TreeNode root, ArrayList<Integer> difference){
23         if(root == null)
24             return 0;
25         if(root.left==null && root.right ==null)
26             return 1;
27         int leftH = heightRec(root.left, difference);
28         int rightH = heightRec(root.right,difference);
29         difference.add(Math.abs(leftH-rightH));
30         return Math.max(leftH, rightH )+1;
31     }
bubuko.com,布布扣

 

LeetCode OJ - Balanced Binary Tree,布布扣,bubuko.com

LeetCode OJ - Balanced Binary Tree

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/echoht/p/3707974.html

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