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);
        }
    }
  • 相关阅读:
    卡牌配对
    SNOI2017 礼物
    【BZOJ2893】征服王
    景中人
    钦点
    杨柳
    兼容IE与firefox、chrome的css 线性渐变(linear-gradient)
    使用C# DES解密java DES加密的字符串
    jQuery插件autoComplete使用
    hadoop SQL使用
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196854.html
Copyright © 2011-2022 走看看