653-Two Sum IV - Input is a BST

kevin聰發表於2018-04-25

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

問題描述

給定二叉排序樹和一個目標數, 若二叉排序樹中存在兩個節點的值的和為目標數, 返回true, 否則, 返回false


問題分析

中序遍歷二叉排序樹獲取值的遞增序列, 然後通過兩個指標l和r來做


解法

public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        List<Integer> list = new ArrayList();

        inorder(root, list);
        int l = 0, r = list.size() - 1;
        while(l < r){
            int sum = list.get(l) + list.get(r);
            if(sum == k)   return true;
            if(sum < k)    l++;
            else            r--;
        }

        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);
    }
}

相關文章