Two Sum IV - Input is a BST

Posted 白常福

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Two Sum IV - Input is a BST相关的知识,希望对你有一定的参考价值。

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

 

 

 

 思路:把值放入map中,遍历值,并判断另一个组合数是否在map中即可。
JAVA CODE
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Map<Integer,Integer> map = new HashMap<>();
    int key = 0;
    public boolean findTarget(TreeNode root, int k) {
        // Queue<TreeNode> queue = new ArrayDeque<>();
        // queue.offer(root);
        // while(!queue.isEmpty()){
        //     root = 
        //     if()
        // }
        find(root);
        for (Integer value : map.values()) {
            if(value*2!=k&&map.containsValue(k - value.intValue()))
                return true;
        }
        return false;
    }
    void find(TreeNode rr){
         if(rr != null){
         find(rr.left);
         map.put(new Integer(key++), new Integer(rr.val));
         find(rr.right);
        }
    }    
}

 

以上是关于Two Sum IV - Input is a BST的主要内容,如果未能解决你的问题,请参考以下文章

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

[LeetCode] Two Sum IV - Input is a BST

[leetcode-653-Two Sum IV - Input is a BST]