题目
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/
2 3
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def visit(self, root, cur_path, pathes):
cur_path.append(root.val)
if root.left==None and root.right==None:
pathes.append('->'.join([str(n) for n in cur_path]))
else:
if root.left != None:
self.visit(root.left, cur_path, pathes)
if root.right != None:
self.visit(root.right, cur_path, pathes)
cur_path.pop()
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if root == None:
return []
res = []
self.visit(root,[],res)
return res