文章目录
513.找树左下角的值
层序遍历(迭代)
朴实无华的层序遍历,遍历结束直接得到答案。“最后一层”这样的要求完美符合层次遍历的思路。
class Solution:
from collections import deque
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
if root == None:
return None
queue = deque([root])
records = []
while (len(queue) > 0):
size = len(queue)
temp = []
for _ in range(size):
curr_node = queue.popleft()
if curr_node.left != None:
queue.append(curr_node.left)
if curr_node.right != None:
queue.append(curr_node.right)
temp.append(curr_node.val)
records.append(temp)
return records[-1][0]
前序遍历(递归)
递归的方法还是可行,记录当前得到过的叶子节点的(最大深度,节点值),遍历中不断进行更新,直到遍历完成。但总是没有层次遍历这么直接。
要注意,self.depthLeaf(root.left, level + 1)
实际上进行了回溯,只不过因为传入的 depth 的复制,没有改变 depth 的值。
class Solution:
def __init__(self):
self.max_depth = -1
self.max_depth_first_val = 0
def depthLeaf(self, root: Optional[TreeNode], level: int):
if root.left == None and root.right == None: # find a leaf
if level > self.max_depth:
self.max_depth_first_val = root.val
self.max_depth = level
if root.left != None:
self.depthLeaf(root.left, level + 1)
if root.right != None:
self.depthLeaf(root.right, level + 1)
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
if root == None:
return None
self.depthLeaf(root, 1)
return self.max_depth_first_val
112.路径总和
经典的遍历,因为不需要处理中的节点,所以前中后序的遍历都可以。
这道题的一个考验点是递归函数的参数与返回值,不同的思路对于递归的返回值有不同的要求。
暴力解法
比较直观的遍历,搜索每一条根节点到叶子节点的 path,记录当前 path 的节点值的和。遍历完成后,查看是否有 path sum 符合目标值即可。
由于这种解法总要遍历整棵树,所以递归函数无需返回值,只要更新 path sum 的记录即可。
class Solution:
def pathSum(self, node: Optional[TreeNode], curr_sum: int, results: List[int]) -> None:
curr_sum += node.val
if node.left == None and node.right == None:
results.append(curr_sum)
if node.left != None:
self.pathSum(node.left, curr_sum, results)
if node.right != None:
self.pathSum(node.right, curr_sum, results)
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root == None:
return False
results = []
self.pathSum(root, 0, results)
return targetSum in results
单线解法
递归时对于当前的 path 进行记录,如果搜索完当前 path 时发现节点和等于目标值,则可以直接返回 True,否则继续搜索。这种方法的好处在于遇到符合的答案可以直接结束递归,向上传递结果,相对上一种暴力搜索更快一些。
这种解法是搜索任意一条 path,所有的信息都局限于当前 path,所以需要返回值来回传当前 path 的结构,也就需要 bool 的返回值。
class Solution:
def pathSum(self, node: Optional[TreeNode], curr_path: List[int], targetSum: int) -> bool:
curr_path.append(node.val)
if node.left == None and node.right == None:
if sum(curr_path) == targetSum:
return True
# not lead node yet
left_result = right_result = False
if node.left != None:
left_result = self.pathSum(node.left, curr_path, targetSum)
curr_path.pop()
if node.right != None:
right_result = self.pathSum(node.right, curr_path, targetSum)
curr_path.pop()
return left_result or right_result
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root == None:
return False
return self.pathSum(root, [], targetSum)
113.路径总和 II
引用和 copy 的区别真的很关键!append
任何可变类型(例如 list)的时候一定要三思而后行啊!不然结果里的 list 只会面目全非。
和上一题的暴力解法一样,搜索整棵树的所有 path,所以递归函数不需要返回值(当前 path 的更新直接记录即可)。
class Solution:
def path(self, node: Optional[TreeNode], targetSum: int, curr_path: List[int], results: List[List[int]]) -> None:
curr_path.append(node.val)
if node.left == None and node.right == None:
if sum(curr_path) == targetSum:
results.append(curr_path.copy())
if node.left != None:
self.path(node.left, targetSum, curr_path, results)
curr_path.pop()
if node.right != None:
self.path(node.right, targetSum, curr_path, results)
curr_path.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if root == None:
return []
results = []
self.path(root, targetSum, [], results)
return results
106.从中序与后序遍历序列构造二叉树
题目中很重要的一个假设:没有重复元素。这是我们可以通过值来定位其位置。
核心思想是,后序遍历的最后一个元素必然是当前树的根节点,由此可以对当前树进行切分。步骤如下:
- 如果后序数组为空,则当前的节点是空节点。
- 如果后序数组非空,则数组的最后一个元素即为当前根节点的值。
- 找到当前根节点在中序数组中的 index,其左侧即为当前节点的左中序数组,右侧为当前节点的右中序数组。
- 根据数组大小,在后续数组中从左往右找到左后序数组和右后序数组。
- 递归处理左右区间。
在处理过程中,另一个重要的性质是,中序数组和后序数组的大小应该是相等的,毕竟代表着同一棵树。
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
# 1. nothing is left, this is None node
if len(postorder) == 0:
return None
# 2. find the current root node
curr_root_value = postorder[-1]
curr_root = TreeNode(val=curr_root_value)
# 3. cut the left_inorder_subtree and right_inorder_subtree
root_idx = 0
while (root_idx < len(inorder)):
if inorder[root_idx] == curr_root_value:
break
root_idx += 1
left_inorder_subtree = inorder[:root_idx]
right_inorder_subtree = inorder[root_idx + 1:]
# 4. cut the left_postorder_subtree and right_inorder_subtree
left_postorder_subtree = postorder[:root_idx]
right_postorder_subtree = postorder[root_idx: len(postorder) - 1]
# recursion over subtrees
curr_root.left = self.buildTree(left_inorder_subtree, left_postorder_subtree)
curr_root.right = self.buildTree(right_inorder_subtree, right_postorder_subtree)
return curr_root
这个解法清晰而直接,不过在递归中一直构造新的 list 会导致较高的时间和空间复杂度,这一点不太好。在下一题中会给出一个更好一些的写法。
105.从前序与中序遍历序列构造二叉树
和上一题一模一样,还是通过前序开头的元素来确定根节点。但为了降低复杂度,这里在递归中传递左右区间的 index 而不是直接传递新的数组。
但不得不说,这个写法实在是太复杂了,很容易出现变量名的混淆,如果有小的 typo 那就尴尬了。
class Solution:
def buildByIndex(self, preorder: List[int], inorder: List[int], preorder_start: int, preorder_end: int, inorder_start: int, inorder_end: int) -> Optional[TreeNode]:
# the subtree has [start, end) as a common list
# 1. empty preorder, return None
if preorder_start == preorder_end:
return None
# 2. find the root node value
curr_root_value = preorder[preorder_start]
curr_root = TreeNode(val=curr_root_value)
# 3. find the left_inorder_subtree and right_inorder_subtree
root_idx = inorder_start
while (root_idx < inorder_end):
if inorder[root_idx] == curr_root_value:
break
root_idx += 1
left_inorder_start, left_inorder_end = inorder_start, root_idx
right_inorder_start, right_inorder_end = root_idx + 1, inorder_end
# 4. find the left_preorder_subtree and right_preorder_subtree
left_preorder_start, left_preorder_end = preorder_start + 1, preorder_start + 1 + (root_idx - inorder_start)
right_preorder_start, right_preorder_end = preorder_start + 1 + (root_idx - inorder_start), preorder_end
# recursion
curr_root.left = self.buildByIndex(preorder, inorder, left_preorder_start, left_preorder_end, left_inorder_start, left_inorder_end)
curr_root.right = self.buildByIndex(preorder, inorder, right_preorder_start, right_preorder_end, right_inorder_start, right_inorder_end)
return curr_root
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
return self.buildByIndex(preorder, inorder, 0, len(preorder), 0, len(inorder))
讨论
前序+中序,后序+中序,都已经被证明可以确定一颗唯一的二叉树(但其实元素不重复已经是很苛刻的前提条件)。但是,前序+后序不可以。朴素的想法是,“中左右”+“左右中”无法分割左右区间。
反例如下:
tree1 的前序遍历是[1, 2, 3]
,后序遍历是[3, 2, 1]
tree2 的前序遍历是[1, 2, 3]
,后序遍历是[3, 2, 1]
然而这是两棵不同的树。