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);
        }
    }
  • 相关阅读:
    数据库迁移到Amazon RDS 的问题
    排序算法之希尔排序
    第一个 Shell脚本
    排序算法之直接插入排序
    当前工作参考
    cerr
    阿里云典型应用案例
    云服务引擎ACE
    阿里云SLB
    指针使用注意事项
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196854.html
Copyright © 2011-2022 走看看