leetcode 653 两数之和 IV - 输入BST

160 阅读1分钟

leetcode 653 两数之和 IV - 输入BST

思路

  1. 前序遍历 BST,转为数组;
  2. 此时数组有序,双指针不断接近 target;

题解

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        vector<int> res;
        inorder(root,res);
        int left = 0;
        int right = res.size()-1;
        while(left < right) {
            int sum = res[left] + res[right];
            if(sum == k) return true;
            else if(sum < k) { //和比目标值小,则移动左指针 
                left++;
            } else {
                right--; //和比目标值大,则移动右指针 
            }
        }
        return false;
    }
    void inorder(TreeNode *root,vector<int> &res) {
        if(root != NULL) {
            inorder(root->left,res);
            res.push_back(root->val);
            inorder(root->right,res);
        }
    }
};