653. Two Sum IV - Input is a BST

Posted ordili

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了653. Two Sum IV - Input is a BST相关的知识,希望对你有一定的参考价值。

1. Question:

653. Two Sum IV - Input is a BST

url: https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input: 
    5
   /   3   6
 /    2   4   7

Target = 9

Output: True

 

Example 2:

Input: 
    5
   /   3   6
 /    2   4   7

Target = 28

Output: False

 

2. Solution

# 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 inOrder(self, root, path_li):
        if root is None:
            return

        self.inOrder(root.left, path_li)
        path_li.append(root.val)
        self.inOrder(root.right, path_li)

    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        value_list = []
        self.inOrder(root, value_list)
        if len(value_list) <= 1:
            return False

        for item in value_list:
            sub = k - item
            if sub != item and sub in value_list:
                return True
            if sub == item and value_list.count(sub) >= 2:
                return True

        return False

 

 

 

 

以上是关于653. Two Sum IV - Input is a BST的主要内容,如果未能解决你的问题,请参考以下文章

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

[leetcode-653-Two Sum IV - Input is a BST]

leetcode 653. Two Sum IV - Input is a BST

LeetCode 653. Two Sum IV - Input is a BST