leetcode 110. Balanced Binary Tree

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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def helper(node):
            if not node:
                return True, 0       
            l_b, l_h = helper(node.left)
            r_b, r_h = helper(node.right)
            if not l_b or not r_b or abs(l_h-r_h) > 1:
                return False, max(l_h, r_h)+1
            return True, max(l_h, r_h)+1
         
        ans, _ = helper(root)
        return ans

或者是直接在获取tree高度的时候用一个成员变量来记录是否平衡。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.ans = True
        def get_depth(node):
            if not node:
                return 0       
            l, r = get_depth(node.left), get_depth(node.right)
            if abs(l-r) > 1:
                self.ans = False
            return max(l, r)+1
         
        get_depth(root)
        return self.ans

 

另外的解法就是使用高度是否为-1来标识是否平衡。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class solution {
public:
int dfsHeight (TreeNode *root) {
        if (root == NULL) return 0;
         
        int leftHeight = dfsHeight (root -> left);
        if (leftHeight == -1) return -1;
        int rightHeight = dfsHeight (root -> right);
        if (rightHeight == -1) return -1;
         
        if (abs(leftHeight - rightHeight) > 1return -1;
        return max (leftHeight, rightHeight) + 1;
    }
    bool isBalanced(TreeNode *root) {
        return dfsHeight (root) != -1;
    }
};

 最笨的方法就是N^2复杂度的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
class Solution:
    # @param {TreeNode} root
    # @return {boolean}
    def isBalanced(self, root):
        if not root:
            return True
 
        return abs(self.getHeight(root.left) - self.getHeight(root.right)) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right)
 
    def getHeight(self, root):
        if not root:
            return 0
 
        return 1 + max(self.getHeight(root.left), self.getHeight(root.right))

 

 

posted @   bonelee  阅读(169)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-06-13 搜索引擎——用户搜索意图的理解及其难点解析,本质是利用机器学习用户的意图分类
2017-06-13 深入浅出时序数据库之预处理篇——批处理和流处理,用户可定制,但目前流行influxdb没有做
2017-06-13 FreeWheel基于Go的实践经验漫谈——GC是大坑(关键业务场景不用),web框架尚未统一,和c++性能相比难说
2017-06-13 CockroachDB——类似spanner的开源版,底层使用rocksdb存储,mvcc,支持事务,raft一致性,licence是CockroachDB Community License Agreement
2017-06-13 在Twitter信息流中大规模应用深度学习——推文的相关度计算使用了深度学习
点击右上角即可分享
微信分享提示