【easy】653. Two Sum IV - Input is a BST

BST树求得两个节点的和是target

//因为是BST所以中序遍历得到的是递增数组
//这个题的方法就是在一个递增数组中找到两个数的和相加是目标结果
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        vector<int> nums;
        stack<TreeNode*> nodes;
        //写BST树的中序遍历,用到一个stack
        while (!nodes.empty() || root){
            if (root){
                nodes.push(root);
                root = root->left;
            }
            else{
                root = nodes.top();
                nodes.pop();
                nums.push_back(root->val);
                root = root->right;
            }
        }
        //处理nums数组找到两个数的和是目标结果数
        int left = 0;
        int right = nums.size()-1;
        while (left<right){
            int sum = nums[left] + nums[right];
            if (sum == k){
                return true;
            }
            else if (sum < k)
                left ++;
            else 
                right --;
        }
        return false;
    }
};

 

posted @ 2018-01-26 21:21  Sherry_Yang  阅读(95)  评论(0编辑  收藏  举报