1、题目描述:
2、题解:
方法1:DFS递归:
二叉树的前序遍历
设置一个全局的数组paths,然后进行DFS
在DFS里,
遇到非空的节点就返回
把节点加入到path中,
遇到叶子结点就把path加入到paths中,
否则就添加'->'到path中
访问左子树
访问右子树
python代码如下:
# 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]:
paths = []
def dfs(root,path):
if not root:
return
path += str(root.val)
if not root.left and not root.right:
paths.append(path)
else:
path += '->'
dfs(root.left,path)
dfs(root.right,path)
dfs(root,'')
return paths
或者:
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
if not root:return res
def dfs(root,path):
if not root:return
if not root.left and not root.right:
# if path not in res:
res.append(path)
return
if root.left:
dfs(root.left,path + '->' + str(root.left.val))
if root.right:
dfs(root.right,path + '->' + str(root.right.val))
dfs(root,str(root.val))
return res
或者:
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
if not root:return res
def dfs(root,path):
if not root:return
if not root.left and not root.right:
# if path not in res:
path += str(root.val)
res.append(path)
return
if root.left:
dfs(root.left,path + str(root.val) + '->' )
if root.right:
dfs(root.right,path + str(root.val) + '->' )
dfs(root,'')
return res
方法2:非递归
用栈
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
#非递归
if not root:
return []
paths= []
stack = [(root,str(root.val))]
while stack:
node,path = stack.pop()
if not node.left and not node.right:
paths.append(path)
if node.left:
stack.append((node.left,path + '->' + str(node.left.val)))
if node.right:
stack.append((node.right,path + '->' + str(node.right.val)))
return paths
方法3:BFS
用队列
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
#非递归
if not root:
return []
paths= []
stack = [(root,str(root.val))]
while stack:
node,path = stack.pop(0)
if not node.left and not node.right:
paths.append(path)
if node.left:
stack.append((node.left,path + '->' + str(node.left.val)))
if node.right:
stack.append((node.right,path + '->' + str(node.right.val)))
return paths
3、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)