跑次树的遍历,可添加到 hashmap 中维护,就变成两数之和I 了。我添加到了 list 中,应该换一下......列表中的话,应该也可以用双指针!!!
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 findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
if not root or (not root.left and not root.right):
return False
self.values = []
self.inOrder(root)
for i, v in enumerate(self.values):
if self.values[i] != k - v and (k - v) in self.values:
return True
return False
def inOrder(self, node):
if node:
self.inOrder(node.left)
self.values.append(node.val)
self.inOrder(node.right)
最近在研究 golang,没时间写树总结,明天再看看二分......
有疑问加站长微信联系(非本文作者)