对二叉树进行dfs
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def findTarget(self, root, k): 10 """ 11 :type root: TreeNode 12 :type k: int 13 :rtype: bool 14 """ 15 if(root==None): 16 return False 17 18 candidates=set() 19 stack=[root] 20 while len(stack)!=0: 21 cur=stack.pop() 22 23 if k-cur.val in candidates: 24 return True 25 else: 26 candidates.add(cur.val) 27 28 if(cur.left!=None): 29 stack.append(cur.left) 30 31 if(cur.right!=None): 32 stack.append(cur.right) 33 34 return False