【谷歌面试题】有序输出两棵二叉查找树中的元素

题目:给出两棵二叉查找树,有序输出所有元素,时间复杂度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;
			}
		}
	}
}

    原文作者:WalkingInTheWind
    原文地址: https://blog.csdn.net/WalkingInTheWind/article/details/8967725
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞