LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)

AlfredaYu發表於2020-12-23

LeetCode#110.Balanced Binary Tree_Tree/Height/DFS/Recursion

題目

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 left and right subtrees of every node differ in height by no more than 1.

Example 1
Example 2
Example 3

要點

基本概念

root ---> leaves

*Level* 

start from 1 ---> += 1

*Depth* 
start from 0 ---> += 1
or = Level -1

*Height* 
start from max(depth) ---> -= 1

參考資料

Tree: Height/Depth/Level

解題

解法一

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        “””
        def check(root):
            if not root: return 0
            left = check(root.left)
            right = check(root.right)
            if left == -1 or right == -1 or abs(left-right) > 1:
                return -1
            return 1 + max(left, right)
        
        return check(root) != -1

解法二

class Solution(object):
    def height(self, root):
        if not root: return -1
        return 1 + max(self.height(root.left), self.height(root.right))
    
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root: return True
        return abs(self.height(root.left) - self.height(root.right)) < 2 \
    and self.isBalanced(root.left) \
    and self.isBalanced(root.right)

相關文章