LeetCode知识点总结 - 653

LeetCode 653. Two Sum IV - Input is a BST

考点 难度
Hash Table Easy
题目

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

思路

定义一个新function,作用是对给定的tree node查找相加和为k的node。用HashSet存储没有配对的node,之后node的另一半都从HashSet里面找。

答案
class Solution {
        HashSet<Integer> set=new HashSet<>();
    public boolean findTarget(TreeNode root, int k) {
        if(root==null) return false;
        if(set.contains(k-root.val)) return true;
        set.add(root.val);
        return findTarget(root.left,k) || findTarget(root.right,k);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_59773145/article/details/120556652