LeetCode题解--653. 两数之和 IV - 输入 BST

1. 题目

给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
输入:

    5
   / \
  3   6
 / \   \
2   4   7
Target = 9
输出: True
输入: 
    5
   / \
  3   6
 / \   \
2   4   7
Target = 28
输出: False

2. 分析

3. C++程序

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        vector<int> st;
        inorder(root,st);
        if(st.size()==0) return false;
        int small=0,big=st.size()-1;
        while(small<big){
            if((st[small]+st[big])==k) return true;
            else if((st[small]+st[big])<k) small++;
            else big--;
        }
        return false;
    }
    void inorder(TreeNode* root,vector<int> &st){
        if(root==NULL) return;
        inorder(root->left,st);
        st.push_back(root->val);
        inorder(root->right,st);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33297776/article/details/81218177
今日推荐