[LeetCode] 653. 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
Thought process:
In-order traversal.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean findTarget(TreeNode root, int k) { List<Integer> nodes = new ArrayList<>(); inOrder(root, nodes); int i = 0; int j = nodes.size() - 1; while (i < j) { int left = nodes.get(i); int right = nodes.get(j); if (left + right < k) { i++; } else if (left + right == k) { return true; } else { j--; } } return false; } private void inOrder(TreeNode root, List<Integer> nodes) { if (root == null) { return; } inOrder(root.left, nodes); nodes.add(root.val); inOrder(root.right, nodes); } } |
Time complexity: O(n).
Comments
Post a Comment