Lintcode record ·, lintcode record
Singleton mode: The Singleton mode is implemented in C #. The difference in python is that the static methods in the class are written differently. python is called a class method. @ classmethod is added before the function.
class Solution: # @return: The same instance of this class every time __m_Solution=None @classmethod def getInstance(self): # write your code here if self.__m_Solution == None: self.__m_Solution=Solution() return self.__m_Solution def __init__(self): pass
Traverse the binary tree path and output all the paths with the same value as the given value. Here it is called recursively. It is like changing Recursion to a loop, but it hasn't been implemented for a long time ····
class Solution: # @param {int} target an integer # @return {int[][]} all valid paths def binaryTreePathSum(self, root, target): # Write your code here res = [] path = [] import copy def getallpath(current, path, res): if current == None: return path.append(current.val) if current.left != None: getallpath(current.left,copy.deepcopy(path), res) if current.right != None: getallpath(current.right,copy.deepcopy(path),res) if current.left is None and current.right is None: res.append(path) getallpath(root,path,res) ps=[] for p in res: sum=0 for v in p: sum=sum+v if sum==target:ps.append(p) return ps