C++Leetcode653:两数之和 IV - 输入BST

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

案例 1:
在这里插入图片描述
案例 2:
在这里插入图片描述
思路
1、暴力解法。中序遍历二叉树,将每个节点的值存入一个动态数组,然后再二层遍历数组判断是否存在两数之和。

实现方法
一、暴力解法

/**
 * 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> res;
        sort(root,res);
        
        for(int i=0;i<res.size()-1;i++){
            for(int j=i+1;j<res.size();j++){
                if(res[i]+res[j]==k)
                    return true;
            }
        }
        return false;
    }
    
    void sort(TreeNode* root,vector<int> &res){
        if(root){
            sort(root->left,res);
            res.push_back(root->val);
            sort(root->right,res);
        } 
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43434305/article/details/87883122