中级农民
- 积分
- 107
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-9-12
- 最后登录
- 1970-1-1
|
I. 可以用stack去迭代BST不断取出下一个元素进行比较(类似于两个list用双指针去求common elements),空间复杂度为O(k),k为BST的深度
II. 也可以用递归的方法做,根据root的大小分三种情况,空间复杂度为O(1) (不考虑递归本身的堆栈。。)
- class Solution {
- public:
- vector<int> result;
- vector<int> findCommon(TreeNode *rootA, TreeNode *rootB) {
- findElement(rootA, rootB);
- return result;
- }
- void findElement(TreeNode *rootA, TreeNode *rootB) {
- if (!rootA || !rootB) return;
- if (rootA->val == rootB->val) {
- result.push_back(rootA->val);
- findElement(rootA->left, rootB->left);
- findElement(rootA->right, rootB->right);
- }
- else if (rootA->val < rootB->val) {
- findElement(rootA, rootB->left);
- findElement(rootA->right, rootB);
- }
- else {
- findElement(rootA->left, rootB);
- findElement(rootA, rootB->right);
- }
- }
- };
复制代码 |
|