-
[Algo Rhythm🕺💃] LeetCode 653. Two Sum IV - Input is a BSTAlgo Rhythm🕺💃/LeetCode 2020. 8. 24. 15:24
📚 Problem description
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: TrueExample 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False🎯 Solution
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean findTarget(TreeNode root, int k) { List<Integer> list = new ArrayList<>(); inorder(root, list); int left = 0, right = list.size() - 1; while(left < right) { int sum = list.get(left) + list.get(right); if(sum == k) return true; if(sum > k) right--; if(sum < k) left++; } return false; } public void inorder(TreeNode root, List<Integer> list) { if(root == null) return; inorder(root.left, list); list.add(root.val); inorder(root.right, list); } }🧐 Approach
BST is half-sorted data structure. We can get sorted array from BST by in-order traversal.
After getting sorted array, we can use two pointer approach to find two indexes.
📖 What I learned
'Algo Rhythm🕺💃 > LeetCode' 카테고리의 다른 글
[Algo Rhythm🕺💃] LeetCode 720. Longest Word in Dictionary (0) 2020.09.04 [Algo Rhythm🕺💃] LeetCode 208. Implement Trie (Prefix Tree) (0) 2020.09.03 [Algo Rhythm🕺💃] LeetCode 167. Two Sum II - Input array is sorted (0) 2020.08.24 [Algo Rhythm🕺💃] LeetCode 78. Subsets (0) 2020.08.22 [Algo Rhythm🕺💃] LeetCode 90. SubsetsII (0) 2020.08.22