标签:递归 ble ret 函数 技术分享 lse png 优秀 变量
class Solution: def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ all_re=[] res=‘‘ return self.dsf(root,all_re) def dsf(self,root,all_res): if not root.right and not root.left: return all_res.append(res[2:]) if root.left: string=‘->%d‘%root.left.val res+=string dsf(root.left) if root.right: string=‘->%d‘%root.left.val res+=string dsf(root.right) return all_res
class Solution: r_list = [] def __init__(self): self.r_list = [] def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ self.__init__() if not root: return self.r_list if (not root.left and not root.right): self.r_list.append(str(root.val)) if root.left: self.recur_node(root.left, str(root.val)) if root.right: self.recur_node(root.right, str(root.val)) return self.r_list def recur_node(self, point, current_string): """ type point: TreeNode retun type: void """ r_string = current_string + "->" + str(point.val) if (not point.left and not point.right): self.r_list.append(r_string) return if point.left: self.recur_node(point.left, r_string) if point.right: self.recur_node(point.right, r_string) return
全局变量也可以写在solution下面
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
循环的做法
class Solution: def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ def dsf(root,path): if root: path += str(root.val) if not root.right and not root.left: paths.append(path) else: path+=‘->‘ dsf(root.right,path) dsf(root.left,path) paths=[] dsf(root,‘‘) return paths
迭代,把函数写在函数里面
class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): res, path_list = [], [] self.dfs(root, path_list, res) return res def dfs(self, root, path_list, res): if not root: return path_list.append(str(root.val)) if not root.left and not root.right: res.append(‘->‘.join(path_list)) if root.left: self.dfs(root.left, path_list, res) if root.right: self.dfs(root.right, path_list, res) path_list.pop()
函数并列假设,要想改变他的值,一路带着走
1.对递归使用的情况不熟悉,特别是这种有全局变量和局部变量的,不知道怎么处理
2.
标签:递归 ble ret 函数 技术分享 lse png 优秀 变量
原文地址:https://www.cnblogs.com/captain-dl/p/10340113.html