欢迎访问我的lintcode题解目录https://blog.csdn.net/richenyunqi/article/details/80686719
散列:
算法设计:
对整棵树作先根遍历。定义一个散列表unordered_set<int>s,存储遍历过的树节点的值。当遍历到某个树节点root时,查看s中是否有n-root->val元素,如果有,说明找到了答案,直接输出;如果没有,递归查找左右子树即可。
C++代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { private: unordered_set<int>s; public: /* * @param : the root of tree * @param : the target sum * @return: two number from tree witch sum is n */ vector<int> twoSum(TreeNode * root, int n) { // write your code here if(root==nullptr) return {}; if(s.find(n-root->val)!=s.cend()) return {root->val,n-root->val}; s.insert(root->val); vector<int>v1=twoSum(root->left,n),v2=twoSum(root->right,n); return v1.empty()?v2:v1; } };
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 of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { private: vector<int>v; public: /* * @param : the root of tree * @param : the target sum * @return: two number from tree witch sum is n */ void inOrder(TreeNode*root){ if(root==nullptr) return; inOrder(root->left); v.push_back(root->val); inOrder(root->right); } vector<int> twoSum(TreeNode * root, int n) { // write your code here inOrder(root); for(int i=0,j=v.size()-1;i<j;){ if(v[i]+v[j]==n) return {v[i],v[j]}; if(v[i]+v[j]<n) ++i; else --j; } return {}; } };