欢迎访问我的leetcode题解目录https://blog.csdn.net/richenyunqi/article/details/80689211
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
散列:
算法设计:
对整棵树作先根遍历。定义一个散列表unordered_set<int>s,存储遍历过的树节点的值。当遍历到某个树节点root时,查看s中是否有n-root->val元素,如果有,说明找到了答案,直接输出;如果没有,递归查找左右子树即可。
C++代码:
/** * 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 { private: unordered_set<int>s; public: bool findTarget(TreeNode* root, int k) { if(root==nullptr) return false; if(s.find(k-root->val)!=s.cend()) return true; s.insert(root->val); return findTarget(root->left,k)||findTarget(root->right,k); } };
two pointers:
算法设计:
将整棵树的中根遍历序列存储到一个vector<int>v中,则v中序列必然是有序的。定义两个索引 i=0、j=v.size()-1,当 i<j 时进行循环并进行以下判断:
- 如果v[i]+v[j]>n,令 j 左移一位,--j
- 如果v[i]+v[j]<n,令 i 右移一位,++i
- 如果v[i]+v[j]==n,说明找到了一组符合要求的两个数,输出,退出循环
C++代码:
/** * 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 { private: vector<int>v; public: void inOrder(TreeNode*root){ if(root==nullptr) return; inOrder(root->left); v.push_back(root->val); inOrder(root->right); } bool findTarget(TreeNode* root, int k) { inOrder(root); for(int i=0,j=v.size()-1;i<j;){ if(v[i]+v[j]==k) return true; if(v[i]+v[j]<k) ++i; else --j; } return false; } };