欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 110. Balanced Binary Tree

程序员文章站 2024-03-19 19:17:58
...

题目

LeetCode 110. Balanced Binary Tree

思路

递归遍历左右子树,找到高度。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def balance(self, root):
        if not root:
            return True, 0
        leftFlag, leftHigh = self.balance(root.left)
        rightFlag, rightHigh = self.balance(root.right)
        if not leftFlag or not rightFlag: return False, 0
        if abs(leftHigh - rightHigh) > 1: return False, 0
        return True, max(leftHigh, rightHigh) + 1
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.balance(root)[0]