题目地址:
https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
给定两棵二叉搜索树,返回由它们所有节点值构成的上升序列。
可以直接用非递归中序遍历的办法来做。代码如下:
class Solution {
public:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> res;
stack<TreeNode*> stk1, stk2;
push_left(stk1, root1);
push_left(stk2, root2);
while (stk1.size() || stk2.size()) {
if (stk1.empty() || stk2.size() && stk1.top()->val > stk2.top()->val)
swap(stk1, stk2);
auto t = stk1.top();
stk1.pop();
res.push_back(t->val);
push_left(stk1, t->right);
}
return res;
}
void push_left(stack<TreeNode*>& stk, TreeNode* cur) {
while (cur) {
stk.push(cur);
cur = cur->left;
}
}
};
时间复杂度 O ( n 1 + n 2 ) O(n_1+n_2) O(n1+n2),空间 O ( h 1 + h 2 ) O(h_1+h_2) O(h1+h2)。