Balanced Binary Tree
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.
思路
判断根结点是否平衡,左子树和右子树高度差距小于等于1。然后递归下去判断。
解题
c++版
| 1 | /** | 
python版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # @param root, a tree node
    # @return a boolean
    def isBalanced(self, root):
        if not root:
            return True
        rightH=self.height(root.right)
        leftH=self.height(root.left)
        if leftH-rightH<=1 and leftH-rightH>=-1:
            return self.isBalanced(root.right) and self.isBalanced(root.left)
        else:
            return False
    
    def height(self,root):
        if not root:
            return 0
        else:
            if not root.right:
                return self.height(root.left)+1
            elif  not root.left:
                return self.height(root.right)+1
            else:
                l = self.height(root.left)  
                r = self.height(root.right)  
                if l<r:
                    return r+1
                else:
                    return l+1

