題目:
二叉樹的所有路徑:給定一個二叉樹,返回所有從根節點到葉子節點的路徑。說明: 葉子節點是指沒有子節點的節點。
示例:
輸入:
1
/ \
2 3
\
5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3
思路:
思路較簡單。
程序:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
result = []
def dfs(root, auxiliary):
if not root:
return
if not root.left and not root.right:
auxiliary_auxiliary = "->".join(auxiliary + [str(root.val)])
result.append(auxiliary_auxiliary)
dfs(root.left, auxiliary + [str(root.val)])
dfs(root.right, auxiliary + [str(root.val)])
dfs(root, [])
return result
