Given two binary search trees root1
and root2
, return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8]
题目:将两个二叉搜索树的元素按从小到大排列。
思路:inorder traversal的变体。两个二叉搜索树一起inorder遍历。代码:
/**
* 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 Solution {
public:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
stack<TreeNode*> s1, s2;
TreeNode* n1 = root1, *n2 = root2;
vector<int> res;
while(!s1.empty() || !s2.empty() || n1 || n2){
while(n1){
s1.push(n1);
n1 = n1->left;
}
while(n2){
s2.push(n2);
n2 = n2->left;
}
int choose = 1;
if(s1.empty()) choose = 2;
else if(s2.empty()) choose = 1;
else if(s2.top()->val <= s1.top()->val) choose = 2;
else choose = 1;
if(choose == 1){
res.push_back(s1.top()->val);
n1 = s1.top()->right;
s1.pop();
} else{
res.push_back(s2.top()->val);
n2 = s2.top()->right;
s2.pop();
}
}
return res;
}
};