Python3解leetcode Binary Tree Paths

问题描述:

 

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

 

思路:

二叉树的问题,首先考虑递归算法,用深度优先搜索。

为了体现模块化思想,一般讲DFS算法单独写成一个方法

代码:

 

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def dfs(self,res,root,list1):
10         if root.left == None and root.right == None:#当前节点是叶子节点
11             res.append( '->'.join(list1))
12             return 
13         if root.left != None:#左边不空
14             list1.append(str(root.left.val))
15             self.dfs(res,root.left,list1)
16             list1.pop()
17         if root.right != None:#右边不空
18             list1.append(str(root.right.val))
19             self.dfs(res,root.right,list1)
20             list1.pop()
21         
22     def binaryTreePaths(self, root):
23         """
24         :type root: TreeNode
25         :rtype: List[str]
26         """
27         if root == None:
28             return []
29         res = []
30         self.dfs(res,root,[str(root.val)])
31         return res

 由于用list作为参数时,list参数可以视为全局变量,这样在任意一个层次的调用中,对list的更改都会影响所有层次调用中的list。

 1 class Solution:
 2     def dfs(self,res,root,str1):
 3         if root.left == None and root.right == None:#当前节点是叶子节点
 4             res.append(str1)
 5             return
 6         
 7         str1 = str1 + '->'
 8         if root.left != None:#左边不空
 9             self.dfs(res,root.left,str1+str(root.left.val))
10         if root.right != None:#右边不空
11             self.dfs(res,root.right,str1+str(root.right.val))
12         
13     def binaryTreePaths(self, root):
14         """
15         :type root: TreeNode
16         :rtype: List[str]
17         """
18         if root == None:
19             return []
20         res = []
21         self.dfs(res,root,str(root.val))
22         return res
23     

上述代码用str传递参数,即为当前调用的局部参数,这时候就不需要每次调用完dfs后再pop()一次了,整体代码简洁一些

res仍旧是传递地址,可视为全局变量

 

posted on 2019-07-15 19:54  狂奔的蜗牛163  阅读(212)  评论(0编辑  收藏  举报