653. Two Sum IV - Input is a BST

xiaoxiao2021-02-28  92

题目:

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 思路:

本题,先利用先序遍历将结点值存储在数组里,再用find函数查找(k-当前结点)是否存在

代码:

/** * 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: vector<int> res; bool findTarget(TreeNode* root, int k) { Preorder(root); for(int i=0;i<res.size();i++) { int temp =k - res[i]; if(find(res.begin(),res.end(),temp)!=res.begin()+i&&find(res.begin(),res.end(),temp)!=res.end()) return true; } return false; } private: void Preorder(TreeNode* root){ if(root!=NULL) { res.push_back(root->val); Preorder(root->left); Preorder(root->right); } } };

转载请注明原文地址: https://www.6miu.com/read-27950.html

最新回复(0)