1. 程式人生 > >[LeetCode] 653. Two Sum IV - Input is a BST

[LeetCode] 653. Two Sum IV - Input is a BST

題:https://leetcode.com/problems/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

題目大意

找出樹中的兩個元素,使得 兩元素之和 為 target。

思路

使用 中序遍歷得到有序陣列,然後使用 雙指標進行 查詢。

note:搜尋二叉樹 中序遍歷為 有序陣列。

中序遍歷非遞迴版本,root先左遍歷將 所有元素放入 stack中。若root 為空,取出 stack 元素 訪問,將該元素的 右子樹作為新 root。

/**
 * 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> list = new ArrayList<>(); inOrder(root,list); int il = 0 , ir = list.size() - 1; while(il<ir){ int tsum = list.get(il) + list.get(ir); if(tsum <
k) il++; else if(tsum>k) ir--; else { return true; } } return false; } private void inOrder(TreeNode root, List<Integer> list) { Stack<TreeNode> stack = new Stack<>(); while(root!=null || !stack.isEmpty()){ while(root!=null){ stack.push(root); root = root.left; } if(!stack.isEmpty()){ root = stack.pop(); list.add(root.val); root = root.right; } } } }

遞迴版本:

/**
 * 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> list = new ArrayList<>();
        inOrder(root,list);
        int il = 0 , ir = list.size() - 1;
        while(il<ir){
            int tsum = list.get(il) +  list.get(ir);
            if(tsum < k)
                il++;
            else if(tsum>k)
                ir--;
            else {
                return true;
            }
        }
        return false;
    }

    private void  inOrder(TreeNode root, List<Integer> list) {
        if(root == null)
            return;
        inOrder(root.left,list);
        list.add(root.val);
        inOrder(root.right,list);
    }
}