题目:给出两棵二叉查找树,有序输出所有元素,时间复杂度O(n),空间复杂度O(h),h为树的高度
此题就是把两棵二叉查找树的中序遍历过程结合在一起。
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void print2BSTsInSortedOrder(TreeNode *root1, TreeNode *root2)
{
stack<TreeNode *> stk1, stk2;
TreeNode *p1 = root1;
while(p1)
{
stk1.push(p1);
p1 = p1->left;
}
TreeNode *p2 = root2;
while(p2 != NULL)
{
stk2.push(p2);
p2 = p2->left;
}
while(!stk1.empty() || !stk2.empty())
{
if(!stk1.empty())
p1 = stk1.top();
if(!stk2.empty())
p2 = stk2.top();
if(p1 == NULL || (p2 && p2->val <= p1->val))
{
printf("%d ", p2->val);
stk2.pop();
p2 = p2->right;
while(p2 != NULL)
{
stk2.push(p2);
p2 = p2->left;
}
}
else if(p2 == NULL || (p1 && p1->val <= p2->val))
{
printf("%d ", p1->val);
stk1.pop();
p1 = p1->right;
while(p1)
{
stk1.push(p1);
p1 = p1->left;
}
}
}
}