跟随carl代码随想录刷题
语言:python
题目:给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从
根节点
到叶子节点
的路径。
叶子节点 是指没有子节点的节点。
👉示例1:
输入:root = [1,2,3,null,5]
输出:[“1->2->5”,“1->3”]
👉示例 2:
输入:root = [1]
输出:[“1”]
递归
与回溯
是一家的
递归
与回溯
是一一对应的,一定要写在一起
所谓隐形回溯是指:每次递归的path
是以path + '->'
形式给出的,而不是path = path+ '->'
,path并没有被加上'->'
注:如果想明确写出回溯,可以这样:
path += '->'
...
path.pop_back(); # 回溯
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
path = ''
result = []
if not root:
return result
self.traversal(root, path, result)
return result
def traversal(self, cur, path:str, result:list[str]) ->None:
path += str(cur.val)
# 如果当前节点是叶子节点,直接输出
if not cur.left and not cur.right:
result.append(path)
if cur.left:
# + '->'是隐形回溯
self.traversal(cur.left, path + '->', result)
if cur.right:
self.traversal(cur.right, path + '->', result)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
stack, path_st, result = deque([root]), deque(), []
path_st.append(str(root.val))
while stack:
cur = stack.pop()
path = path_st.pop()
# 如果当前节点是叶子节点,就将路径添加到结果中
if not cur.left and not 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