Leetcode 257.二叉树的所有路径

257. 二叉树的所有路径

题目

给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。

示例:

1
2
3
4
5
6
7
8
9
输入:

1
/ \
2 3
\
5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

方法

方法1:递归

递归先序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
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)]
left_paths=self.binaryTreePaths(root.left)
right_paths=self.binaryTreePaths(root.right)
return ['%s->%s' %(root.val,path) for path in left_paths+right_paths]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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 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)]

paths=[str(root.val)+'->'+path for path in self.binaryTreePaths(root.left)]
paths+=[str(root.val)+'->'+path for path in self.binaryTreePaths(root.right)]
return paths
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []

res=[]
self.dfs(root,'',res)
return res

def dfs(self,root,ls,res):
if not root.left and not root.right:
res.append(ls+str(root.val))
if root.left:
self.dfs(root.left,ls+str(root.val)+'->',res)
if root.right:
self.dfs(root.right,ls+str(root.val)+'->',res)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.path=[]
path=''

if not root:
return self.path
self.road(root,path)
return self.path
def road(self,root,path):
path+=str(root.val)+'->'
if root.left:
self.road(root.left,path)
if root.right:
self.road(root.right,path)
if not root.left and not root.right:
self.path.append(path[:-2])

方法2:迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []

res=[]
stack=[(root,'')]
while stack:
node,s=stack.pop()
if not node.left and not node.right:
res.append(s+str(node.val))

if node.right:
stack.append((node.right,s+str(node.val)+'->'))
if node.left:
stack.append((node.left,s+str(node.val)+'->'))
return res

参考资料