zoukankan      html  css  js  c++  java
  • 653. Two Sum IV

    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
  • 相关阅读:
    windows下在yii中使用mongodb
    yii框架便利类CVarDumper使用
    64位虚拟机创建注意事项
    C#中的委托和事件
    Attribute
    NuGet安装及使用教程
    WPF+WEB+WinForm->>表现层共用类
    C#报修系统Ⅱ
    C#带小括号的运算
    工厂模式提供数据源
  • 原文地址:https://www.cnblogs.com/ordili/p/9975708.html
Copyright © 2011-2022 走看看