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);
        }
     
  • 相关阅读:
    python025 Python3 正则表达式
    python024 Python3 实例
    python023 Python3 标准库概览
    python022 Python3 面向对象
    python021 Python3 错误和异常
    列表和元组的元素不可被修改,但列表和元组的元素的元素可以被修改
    织梦标签
    自动添加QQ
    php把时间存入数据库为年月日时分秒类型
    PHP后台批量删除数据
  • 原文地址:https://www.cnblogs.com/wxshi/p/7598374.html
Copyright © 2011-2022 走看看