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

    先inorder traverse,再用two pointer找target sum

    time: O(n)  -- inorder traverse O(n), binary search O(logn), space: O(height)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean findTarget(TreeNode root, int k) {
            List<Integer> nums = new ArrayList<>();
            inorder(root, nums);
            int l = 0, r = nums.size() - 1;
            while(l < r) {
                if(nums.get(l) + nums.get(r) == k) {
                    return true;
                } else if(nums.get(l) + nums.get(r) > k) {
                    r--;
                } else {
                    l++;
                }
            }
            return false;
        }
        
        public void inorder(TreeNode root, List<Integer> nums) {
            if(root == null) {
                return;
            }
            inorder(root.left, nums);
            nums.add(root.val);
            inorder(root.right, nums);
        }
    }
  • 相关阅读:
    NumPy
    NumPy切片和索引
    NumPy来自数值范围的数组
    NumPy来自现有数据的数组
    NumPy数组创建例程
    NumPy数组属性
    hdu 1072 Nightmare
    hdu 1010
    nyoj zb的生日
    Catch That Cow
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196854.html
Copyright © 2011-2022 走看看