LeetCode Two Sum IV - Input is a BST

原题链接在这里:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/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: True

Example 2:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False

题解:

BST inorder traversal 得到ascending的list, 用two pointers 夹比找k.

Time Complexity: O(n), n 是node数.

Space: O(n), list size.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean findTarget(TreeNode root, int k) {
12         List<Integer> list = new ArrayList<Integer>();
13         inorder(root, list);
14         int l = 0; 
15         int r = list.size()-1;
16         while(l < r){
17             if(list.get(l) + list.get(r) == k){
18                 return true;
19             }else if(list.get(l) + list.get(r) < k){
20                 l++;
21             }else{
22                 r--;
23             }
24         }
25         return false;
26     }
27     
28     private void inorder(TreeNode root, List<Integer> list){
29         if(root == null){
30             return;
31         }
32         inorder(root.left, list);
33         list.add(root.val);
34         inorder(root.right, list);
35     }
36 }

或者对每个TreeNode cur在BST中找k-cur.val.

Time Complexity: O(nlogn). 

Space: O(logn), stack space.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean findTarget(TreeNode root, int k) {
12         return dfs(root, root, k);
13     }
14     
15     private boolean dfs(TreeNode root, TreeNode cur, int k){
16         if(cur == null){
17             return false;
18         }
19         return search(root, cur, k-cur.val) || dfs(root, cur.left, k) || dfs(root, cur.right, k);
20     }
21     
22     private boolean search(TreeNode root, TreeNode cur, int target){
23         if(root == null){
24             return false;
25         }
26         
27         if(root.val == target && root != cur){
28             return true;
29         }else if(root.val < target){
30             return search(root.right, cur, target);
31         }else if(root.val > target){
32             return search(root.left, cur, target);
33         }
34         
35         return false;
36     }
37 }

 

posted @ 2017-09-12 08:53  Dylan_Java_NYC  阅读(517)  评论(0编辑  收藏  举报