题目描述:返回二叉树从根到叶子节点的路径。(是无左子树且无右子树)
题目链接:Leetcode 257. Binary Tree Paths
递归添加。
代码如下
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
ans = []
if not root:
return []
self.dfs(root,[],ans)
return ans
def dfs(self,root,path,ans):
if root and not root.left and not root.right:
path.append(str(root.val))
tmp = "->".join(path)
if tmp not in ans:
ans.append(tmp)
return
if root:
self.dfs(root.left,path+[str(root.val)],ans)
self.dfs(root.right,path+[str(root.val)],ans)
非递归
# 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):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
ans = []
s = [(root,[str(root.val)])]
while s:
node,path = s.pop()
if not node.left and not node.right:
# path.append(str(node.val))
ans.append("->".join(path))
if node.right:
# path.append()
p = list(path)
p.append(str(node.right.val))
s.append((node.right,p))
if node.left:
p = list(path)
p.append(str(node.left.val))
s.append((node.left,p))
# s.append((node.left,path+[str(node.left.val)]))
return ans
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: 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
参考链接
- Leetcode 257. Binary Tree Paths直接用字符串,每次
+
都会返回新的字符串。