110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
思路: 判断二叉树是否平衡,也就是二叉树的任何节点的左右子树高度差值不能超过1。这和求子树高度的题目类似。使用递归法时,但凡有个节点的左右子树高度差超过1,就一直return -1了,也就是不满足balanced了。
# 递归法
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
return self.get_hight(root) != -1
def get_hight(self, node):
if not node:
return 0
left = self.get_hight(node.left)
right = self.get_hight(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
# 迭代法
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
height_map = {}
stack = [root]
while stack:
node = stack.pop()
if node:
stack.append(node)
stack.append(None)
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
else:
real_node = stack.pop()
left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0)
if abs(left - right) > 1:
return False
height_map[real_node] = 1 + max(left, right)
return True
257. Binary Tree Paths
Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
思路:这里用迭代法,记录从root到当前节点的路径path于path_st。当当前节点为叶节点后,将到该叶节点的这条路径push入path中。并在处理完stack中所有节点后,输出path。stack后进先出来实现DFS。
class Solution(object):
def binaryTreePaths(self, root):
stack, path_st, result = [root], [str(root.val)], []
while stack:
cur = stack.pop()
path = path_st.pop()
if not (cur.left or cur.right):
result.append(path)
if cur.right:
stack.append(cur.right)
path_st.append(path + '->' + str(cur.right.val))
if cur.left:
stack.append(cur.left)
path_st.append(path + '->' + str(cur.left.val))
return result