Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class BSTIterator{
- public:
- BSTIterator(TreeNode* root, bool rev=false) : reverse(rev){
- push(root);
- }
- void push(TreeNode* root){
- while(root){
- s.push(root);
- root = (reverse)?root->right:root->left;
- }
- }
- int next(){
- TreeNode* tp =s.top();s.pop();
- push(!reverse ? tp->right : tp->left);
- return tp->val;
- }
- private:
- stack<TreeNode*>s;
- bool reverse;
- };
- class Solution {
- public:
- bool findTarget(TreeNode* root, int k) {
- BSTIterator leftItr(root),rightItr(root,true);
- int left = leftItr.next(), right = rightItr.next();
- while(left<right){
- if(left+right == k) return true;
- if(left+right>k)
- right=rightItr.next();
- else
- left=leftItr.next();
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement