1086. Tree Traversals Again (25)

本文介绍了一种通过一系列push和pop操作构建二叉树的方法,并实现了中序遍历来展示二叉树的结构。文章详细解释了如何根据操作序列确定节点之间的父子关系,并附带了完整的AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.如果上次没有弹出,并且栈为空,则这次压入的为根

2.如果上次有弹出,并且这次压入,那么上次弹出的是父节点,这次压入的是右子节点

3如果上次没有弹出,并且这次压入,那么这次压入的是栈头的左子节点

4.每次弹出一个节点,都要把这个节点记录下来,lastPop


AC代码:

//#include<string>
//#include <iomanip>
//#include<stack>
//#include<unordered_set>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<unordered_map>
#include<set>
#include<queue>
#include<map>
#include<vector>
#include <algorithm>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
#include<stack>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode*l, *r;
	TreeNode() :val(-1), l(NULL), r(NULL){};
	TreeNode(int x) :val(x), l(NULL), r(NULL){};
};
void InOrder(TreeNode*root, vector<int>&in)
{
	if (root)
	{
		InOrder(root->l, in);
		InOrder(root->r, in);
		in.push_back(root->val);
	}
}
int main(void)
{
	stack<TreeNode*> sta;
	TreeNode*root = NULL;
	TreeNode*lastPop = NULL;
	int n;
	cin >> n;
	for (int i = 0; i < 2 * n; i++)
	{
		string str;
		cin >> str;
		if (str == "Push")
		{
			int tmp;
			cin >> tmp;
			if (sta.empty() && lastPop == NULL)
			{
				root = new TreeNode(tmp);
				sta.push(root);
			}
			else if (lastPop)
			{//如果上次pop出了,这次压入,证明是右子树
				lastPop->r = new TreeNode(tmp);
				sta.push(lastPop->r);
			}
			else
			{
				sta.top()->l = new TreeNode(tmp);
				sta.push(sta.top()->l);
			}
			lastPop = NULL;//这次是压入,所以没有上次Pop出的元素的值
		}
		else
		{//这次是pop出,所以需要存储pop出的元素
			TreeNode*head = sta.top();
			sta.pop();
			lastPop = head;
		}
	}
	vector<int> in(0);
	InOrder(root, in);
	for (int i = 0; i < in.size(); i++)
	{
		cout << in[i];
		if (i != in.size() - 1)
			cout << " ";
	}
	cout << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值