给定一颗二叉树,返回它从根结点到叶子结点的所有路径
注意:
叶子结点没有子树
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
1:递归
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
pathList = []
if root.left:
pathList += self.binaryTreePaths(root.left)
if root.right:
pathList += self.binaryTreePaths(root.right)
for index, path in enumerate(pathList):
pathList[index] = str(root.val) + "->" +path
return pathList
2:迭代(参考他人)
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
pathList, stack = [], [(root, "")]
while stack:
node, pathStr = stack.pop(0)
if not node.left and not node.right:
pathList.append(pathStr + str(node.val))
if node.left:
stack.append((node.left, pathStr + str(node.val) + "->"))
if node.right:
stack.append((node.right, pathStr + str(node.val) + "->"))
return pathList
算法题来自:https://leetcode-cn.com/problems/valid-anagram/description/