LeetCode OJ - Balanced Binary Tree

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

下面是AC代码:

 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     }

 

转载于:https://www.cnblogs.com/echoht/p/3707974.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值