Loading

LeetCode problem#653

Two Sum IV - Input is a BST

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

44 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 *     int val;
5 *     TreeNode left;
6 *     TreeNode right;
7 *     TreeNode() {}
8 *     TreeNode(int val) { this.val = val; }
9 *     TreeNode(int val, TreeNode left, TreeNode right) {
10 *         this.val = val;
11 *         this.left = left;
12 *         this.right = right;
13 *     }
14 * }
15 */
16class Solution {
17    public boolean findTarget(TreeNode root, int k) {
18        HashSet<Integer> hashSet = new HashSet<Integer>();
19
20        // You can also use a queue for breadth-first
21        Stack<TreeNode> stack = new Stack<TreeNode>();
22        stack.push(root);
23
24        while (!stack.isEmpty()) {
25            TreeNode curr = stack.pop();
26
27            int difference = k - curr.val;
28
29            if (hashSet.contains(difference)) {
30                return true;
31            }
32            hashSet.add(curr.val);
33
34            if (curr.left != null) {
35                stack.push(curr.left);
36            }
37            if (curr.right != null) {
38                stack.push(curr.right);
39            }
40        }
41
42        return false;
43    }
44}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.