• 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);
        }
     
  • 相关阅读:
    中值定理
    poj 3984 迷宫问题 bfs
    android 处理网络状态——无网,2g,3g,wifi,ethernet,other
    POJ 1273 || HDU 1532 Drainage Ditches (最大流模型)
    Android硬件加速
    Android的横竖屏切换
    滑雪_poj_1088(记忆化搜索).java
    Rank of Tetris(hdu1811拓扑排序+并查集)
    git在windows下clone、pull或者push内存溢出的解决办法
    数据库中DDL、DML、DCL和TCP概念
  • 原文地址:https://www.cnblogs.com/wxshi/p/7598374.html
Copyright © 2020-2023  润新知