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

    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

    思路:递归遍历BST(Binary Search Tree)
    class Solution:
        def findTarget(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: bool
            """
            self.root = root
            self.k = k
            return self.searchNumber(root)
            
        def searchNumber(self, root):
            if not root:
                return False
            node = self.root
            n = self.k - root.val
            if n != root.val:
                while node:
                    if node.val == n:
                        return True
                    if n > node.val:
                        node = node.right
                    else:
                        node = node.left
            return self.searchNumber(root.left) or self.searchNumber(root.right)
  • 相关阅读:
    Linux基础ls命令
    Linux基础tree命令
    Java银行调度系统
    Java交通灯系统
    Java反射
    Java基础IO流
    Java多线程
    Java集合框架
    Springmvc的一些属性功能
    JS
  • 原文地址:https://www.cnblogs.com/yancea/p/7510378.html
Copyright © 2011-2022 走看看