Description
Given a binary tree, return all root-to-leaf paths.
Solution
注意使用.pop 和copy.deepcopy管理路径
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
import copy
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def find_path(self,root,path):
if root.left is None and root.right is None:
path.append(root.val)
self.path.append( "->".join(map(str,path)) )
path.pop()
return root.val
path.append(root.val)
if root.left is not None:
self.find_path(root.left,path)
if root.right is not None:
self.find_path(root.right,path)
path.pop()
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
self.path =[]
self.find_path(root,[])
return self.path
更简洁版本,不需要额外储存空间,将path直接转换为str存储
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
if root.left is None and root.right is None:
return [str(root.val)]
left= []
if root.left is not None:
left =self.binaryTreePaths(root.left)
right =[]
if root.right is not None:
right = self.binaryTreePaths(root.right)
path =[]
for p in right+left:
path.append(str(root.val) + '->'+ p)
return path










网友评论