# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 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 inorderTraversal(self, root):
# inorder traversal of the BST
# return a list
if (root is None):
return []
else:
res = []
res.extend(self.inorderTraversal(root.left))
res.append(root.val)
res.extend(self.inorderTraversal(root.right))
return res
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
# first traverse the tree and put everything in a list
nums = self.inorderTraversal(root)
i = 0
j = len(nums)-1
while(i < j):
curr = nums[i] + nums[j]
if (curr == k):
return True
elif (curr > k):
j -= 1
else :
i += 1
return False
1) Note in Python how to check if a node is None: if a is None
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.