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"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
深搜,搜的同时,记录之前的树枝,然后在叶子节点的地方,把路径打印出来。递归到上一层的时候,要把路径的最后一个弹出来
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def __init__(self):
self.path = []
self.res = []
def binaryTreePaths(self, root):
if not root:
return self.res
self.path += root.val,
if root.left == None and root.right == None:
temp = ''
for i in self.path:
temp += str(i) + '->'
self.res += [temp[:-2]]
self.binaryTreePaths(root.left)
self.binaryTreePaths(root.right)
self.path.pop()
return self.res