LC.110. Balanced Binary Tree

https://leetcode.com/problems/balanced-binary-tree/description/
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.


bal. binary tree:

3 3: max(1,2) + 1 = 3
/ \
9 20 9: 1 20:2 (max 1, 1) + 1 = 2
/ \
15 7 both 1

not bal. binary tree:
3 3-1 > 1 not bal. return -1
/ \
9 20 9: 1 ; 20: max(1,2) + 1 = 3
/ \
15 7 15: 1 7: 2
\
9 9: 1


 1 public boolean isBalanced(TreeNode root) {
 2         if (root == null) return true;
 3         return getHeight(root) != -1 ;
 4     }
 5     //get current node height: -1 代表不平衡
 6     private int getHeight(TreeNode root){
 7         //base case: 空叶子高度 = 0 非空叶子高度 = 1
 8         if (root == null) return 0 ;
 9         // post order
10         int l = getHeight(root.left) ;
11         int r = getHeight(root.right) ;
12         int diff = Math.abs(l-r) ;
13         //如果当前节点下左右子树 不平衡 或者 高度 差值 》 1 则 当前节点返回 不平衡 -1
14         if (l == -1 || r == -1 || diff > 1) {
15             return - 1 ;
16         }
17         //如果平衡,返回 正常高度
18         return Math.max(l,r) + 1 ;
19     }

 



转载于:https://www.cnblogs.com/davidnyc/p/8476854.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值