深度优先:首先遍历最低层的节点,然后逐步上移到根节点。
dfs + recursion过于的慢
尽量不使用递归
例
- Binary Tree Paths
Easy
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/
2 3
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
自己写的递归
# 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]:
if root is None:
return []
ls,res='',[]
self.dfs(root,ls,res)
return res
def dfs(self,node,ls,res):
if node.left:
self.dfs(node.left, ls+str(node.val)+'->', res)
if node.right:
self.dfs(node.right, ls+str(node.val)+'->', res)
if node.left is None and node.right is None:
res.append(ls+str(node.val))
别人写的用栈不用递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#用stack代替递归,会快一些嘞
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
res,stack=[],[(root,"")]
while stack:
node, ls = stack.pop()
if not node.left and not node.right:
res.append(ls+str(node.val))
if node.right:
stack.append((node.right, ls+str(node.val)+"->"))
if node.left:
stack.append((node.left, ls+str(node.val)+"->"))
return res
二叉树的最大路径和 #124
找不到快一点的方法 有时间再做一次
网友评论