Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2022-10-09 14:11:02
653. Two Sum IV - Input is a BST
给予一个二元搜寻树和一个数字k,若存在两数相加为k返回true。
Example:
https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
思路:
1.DFS然后把访问完的节点放入HashTable里(这里用Set)
2.每次都检查Set里有没有 k - root.val 有的话返回true,否则都返回false
Java Code:
class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> set = new HashSet<>();
return findTarget(root, k, set);
}
private boolean findTarget(TreeNode root, int k, Set<Integer> set) {
if(root == null) return false;
if(set.contains(k - root.val)) return true;
set.add(root.val);
return findTarget(root.left, k, set) || findTarget(root.right, k,
set);
}
}
我这辈子只写的出Two Sum了= =
作者: wu10200512 (廷廷)   2022-10-09 14:21:00
我还不会two sum :(
作者: SecondRun (雨夜琴声)   2022-10-09 14:22:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com