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