LeetCode刷题实战110:平衡二叉树
共 3638字,需浏览 8分钟
·
2020-11-30 22:35
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.
题意
解题
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
def height(node):
if not node:
return 0
return max(height(node.left), height(node.right)) + 1
if abs(height(root.left) - height(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(node):
if not node:
return 0
left = height(node.left)
right = height(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return height(root) != -1
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
nodes = [root]
for node in nodes:
if node:
nodes.extend([node.left, node.right])
depths = {}
nodes.reverse()
for node in nodes:
if node:
if abs(depths.get(node.left, 0) - depths.get(node.right, 0)) > 1:
return False
depths[node] = max(depths.get(node.left, 0), depths.get(node.right, 0)) + 1
return True
我们也可以通过前序遍历的方式去更新节点的深度。但是这里的问题和之前的Leetcode 144:二叉树的前序遍历中有一些区别,之前的问题中是输出节点,而我们这里是要更新节点。所以我们不能直接将节点弹出,而是要保留到更新完节点后再弹出。这要怎么做呢?我们可以通过建立一个tuple包含一个seen信息,表示这个节点之前是不是访问过。如果访问过我们再将节点弹出,否则的话再将节点插回去。
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
stack = list()
stack.append((root, 0))
depths = {}
while stack:
node, seen = stack.pop()
if node:
if not seen:
stack.extend([(node, 1), (node.right, 0), (node.left, 0)])
if abs(depths.get(node.left,0) - depths.get(node.right,0)) > 1:
return False
depths[node] = max(depths.get(node.left,0), depths.get(node.right,0)) + 1
return True
更多推文:
LeetCode刷题实战105:从前序与中序遍历序列构造二叉树