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
解法一: time and space O(n)
/** * 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) { HashSet<Integer> set = new HashSet<Integer>(); return findTargetHelper(root,set,k); } public boolean findTargetHelper(TreeNode node, HashSet set, int k) { if(node == null) return false; if(set.contains(k-node.val)) return true; set.add(node.val); return findTargetHelper(node.left, set, k) || findTargetHelper(node.right, set, k); } }
解法二:time and space O(n)。 recursion不需要返回值
/** * 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) { ArrayList<Integer> list = new ArrayList<Integer>(); inOrder(root,list); int start = 0; int end = list.size()-1; while(start < end) { if(list.get(start)+list.get(end) == k) return true; if(list.get(start)+list.get(end) > k) end --; else start ++; } return false; } public void inOrder(TreeNode root, ArrayList<Integer> list) { if(root == null) return; inOrder(root.left,list); list.add(root.val); inOrder(root.right,list); } }
解法三:看不懂!
Use the stack and search just like 2sum without dumping all the value out in the beginning.
-- Time/Space: n/logn in average
public boolean findTarget(TreeNode root, int k) { if(root == null) return false; Stack<TreeNode> l_stack = new Stack<>(); Stack<TreeNode> r_stack = new Stack<>(); stackAdd(l_stack, root, true); stackAdd(r_stack, root, false); while(l_stack.peek() != r_stack.peek()){ int n = l_stack.peek().val + r_stack.peek().val; if(n == k){ return true; }else if(n > k){ stackNext(r_stack, false); }else{ stackNext(l_stack, true); } } return false; } private void stackAdd(Stack<TreeNode> stack, TreeNode node, boolean isLeft){ while(node != null){ stack.push(node); node = (isLeft) ? node.left : node.right; } } private void stackNext(Stack<TreeNode> stack, boolean isLeft){ TreeNode node = stack.pop(); if(isLeft){ stackAdd(stack, node.right, isLeft); }else{ stackAdd(stack, node.left, isLeft); } }