1、二叉树合并问题,题目参考leetcode617,给定两个二叉树,目标是合并,两个都有节点的相加,只有一个的保留,使用递归方法可以写如下代码。
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1:
return root2
if not root2:
return root1
merged = TreeNode(root1.val + root2.val)
merged.left = self.mergeTrees(root1.left, root2.left)
merged.right = self.mergeTrees(root1.right, root2.right)
return merged
2、二叉树寻找路径问题,题目参考leetcode257,给你一个节点root,按任意顺序返回所有从根节点到叶子节点的路径。这题的关键遍历所有节点,同时保留路径作为前缀,如果该节点为叶子节点,则保存路径,否则继续遍历,因为涉及到保存前缀,因此新构建了一个函数用来遍历。
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def construct_paths(root, path):
if not root:
return
path += str(root.val)
if not root.left and not root.right:
paths.append(path)
else:
path += '->'
construct_paths(root.left, path)
construct_paths(root.right, path)
paths = []
construct_paths(root, "")
return paths