interview_prepare_binarytree

1.pathSum

 1 class TreeNode:
 2     def __init__(self,x):
 3         self.val=x
 4         self.left=None
 5         self.right=None
 6 
 7 
 8 class Solution:
 9     def dfs(self,root,target,path):
10         if(root.left==None and root.right==None and root.val+sum(path)==target):
11             self.res.append(path+[root.val])
12             return
13         
14         if(root.left):
15             self.dfs(root.left,target,path+[root.val])
16         
17         if(root.right):
18             self.dfs(root.right,target,path+[root.val])
19 
20     def pathSum_dfs(self,root,target):
21         self.res=[]
22         if(not root):
23             return []
24 
25         self.dfs(root,target,[])
26 
27         return self.res
28 
29 
30 
31 
32 root=TreeNode(5)
33 l11=TreeNode(4)
34 l12=TreeNode(8)
35 l21=TreeNode(11)
36 l23=TreeNode(13)
37 l24=TreeNode(4)
38 l31=TreeNode(7)
39 l32=TreeNode(2)
40 l35=TreeNode(5)
41 l36=TreeNode(1)
42 
43 root.left=l11
44 root.right=l12
45 l11.left=l21
46 l12.left=l23
47 l12.right=l24
48 l21.left=l31
49 l21.right=l32
50 l24.left=l35
51 l24.right=l36
52 
53 print(Solution().pathSum_dfs(root,22))

 

# Definition for a binary tree node. # class TreeNode(object): #     def __init__(self, x): #         self.val = x #         self.left = None #         self.right = None
class Solution(object):     def dfs(self,root,target,path):         if(root.left==None and root.right==None and root.val+sum(path)==target):             self.res.append(path+[root.val])             return                  if(root.left):             self.dfs(root.left,target,path+[root.val])                  if(root.right):             self.dfs(root.right,target,path+[root.val])

    def pathSum(self, root, sum):         self.res=[]         if(not root):             return []
        self.dfs(root,sum,[])
        return self.res
上一篇:Oracle数据库在给表添加字段的sql中用comment报错


下一篇:175210闵天 《网络对抗技术》Exp8 Web基础