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
    看的其他coder给出的答案,很详细。

    方法1

    Two sum问题可以转化为查找一个数值问题,Target-node.val,主要思想是使用Hashset存储二叉搜索树的节点,对BST进行遍历,当每次插入一个节点时候,判断set中是否存Target-node.val
    /**
     * 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) {
            HashSet<Integer> set = new HashSet();
            return dfs(root,set,k);
            
        }
        public boolean dfs(TreeNode root, HashSet<Integer> set ,int k)
        {
            if(root == null) return false;
            if(set.contains(k - root.val)) return true;
            set.add(root.val);
            return dfs(root.left, set, k) || dfs(root.right, set, k);
        }
    }

    方法2

    这种方法和常规的TwoSum问题类似,先得到排序的数组,恰好二叉搜索树的中序遍历就是有序的数组,使用两个指针分别指向数组的首和尾,判断nums[i]+nums[j]的和与Target的关系。
       public boolean findTarget(TreeNode root, int k) {
            List<Integer> nums = new ArrayList<>();
            inorder(root, nums);
            for(int i = 0, j = nums.size()-1; i<j;){
                if(nums.get(i) + nums.get(j) == k)return true;
                if(nums.get(i) + nums.get(j) < k)i++;
                else j--;
            }
            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);
        }
     
  • 相关阅读:
    3个检测浏览器UserAgent信息的网站
    linux系统下配置网桥(CentOS 5.5)
    squid封禁不带UserAgent的请求
    iptables透明网桥无法使用透明代理错误
    Squid修改用户浏览器的Useragent信息
    MySQL主从复制(MasterSlave)与读写分离(MySQLProxy)实践
    js中格式化时间
    js获取当前月的第一天和最后一天
    JS String.toDate
    Js获取当前日期时间及其它操作
  • 原文地址:https://www.cnblogs.com/wxshi/p/7598374.html
Copyright © 2011-2022 走看看