LeetCode 110. Balanced Binary Tree
程序员文章站
2024-03-19 19:17:58
...
题目
思路
递归遍历左右子树,找到高度。
代码
# 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]
上一篇: 【第1126期】重新组织git本地提交
下一篇: 1174 区间中最大的数
推荐阅读
-
Leetcode 110. Balanced Binary Tree
-
[LeetCode]110. Balanced Binary Tree
-
LeetCode 110. Balanced Binary Tree
-
LeetCode 110. Balanced Binary Tree
-
【LeetCode】Balanced Binary Tree(平衡二叉树)
-
leetcode--minimum-depth-of-binary-tree
-
[Leetcode][python]Minimum Depth of Binary Tree
-
LeetCode:102.Binary Tree Level Order Traversal
-
LeetCode 662 Maximum Width of Binary Tree 二叉树的最大宽度
-
[leetcode]662. Maximum Width of Binary Tree(Python)