7-5 Tree Traversals Again

03-树3 Tree Traversals Again (25分) 03-树3 Tree Traversals Again (25分)An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered f 阅读详情

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.


         Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

 

       题意:用栈的push、pop操作给出一棵二叉树的中序遍历顺序,求这棵二叉树的后序遍历。

       这道题我写了两种解法,第一种需要建立树,具体如下:

       需要一个堆栈s,一个child变量(表示该当前结点是其父亲结点的左儿子还是右儿子),父亲结点变量fa
对于push x操作:
1).第一个push的肯定是根节点root。
2).根据child变量,建立fa与x的父子关系,fa = x;
3).由于是中序遍历,所以接下来的结点必定是x的左儿子(如果有的话),child = LEFT;
4).然后进行Push x操作,因为未来还要输入x的右儿子(如果有的话),此时有必要记住x结点

对于pop操作:
1).根据中序遍历性质,可知接下来的结点必定是当前堆栈顶部结点的右儿子(如果有的话),因此fa = Pop(),child = RIGHT;

 

代码实现如下:

#include<stdio.h>
#include<stdlib.h> 
#include<string.h>

#define ElementType int
#define MaxN 35
#define LEFT 0
#define RIGHT 1

typedef struct SNode *Stack;
struct SNode{
	ElementType *data;
	int top;
	int MaxSize; 
};

struct TreeNode{
	int left;
	int right;
}node[MaxN];

Stack CreateStack(int MaxSize); 
void Push(Stack PtrS,ElementType X);
ElementType Pop(Stack PtrS);
void PostOrderTraversal(int r);

int main()
{
	int N,x;
	int root = -1,fa;
	int child = LEFT;
	char str[10];
	
	Stack s = CreateStack(100);
	memset(node,-1,sizeof(node));
	scanf("%d",&N);
	for(int i=0; i<2*N; i++){
		scanf("%s",str);
		if(strcmp(str,"Push") == 0){
			scanf("%d",&x);
			if(root == -1){
				root = x;  //第一个输入的必是根结点 
			}else{
				if(child == LEFT){
					node[fa].left = x;
				}else{
					node[fa].right = x;
				}
			} 
			fa = x;
			child = LEFT;
			Push(s,x);
		}else{
			fa = Pop(s);
			child = RIGHT;
		}
	}
	PostOrderTraversal(root);
	
	return 0;
}

/*****后序遍历*****/ 
void PostOrderTraversal(int r)
{
	static int first = 1;
	
	if(r != -1){
		PostOrderTraversal(node[r].left);
		PostOrderTraversal(node[r].right);
		if( first ){
			first = 0;
			printf("%d",r);
		}else{
			printf(" %d",r);
		}
	}
}

//建立空栈 
Stack CreateStack(int MaxSize)
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
    S->top = -1;
    S->MaxSize = MaxSize;
    
    return S;
}

//入栈
void Push(Stack S,ElementType X)
{
	if(S->top == S->MaxSize-1)
	    printf("堆栈满\n");  
	else
	    S->data[++(S->top)] = X;
 } 
//出栈
#define Error -1
ElementType Pop(Stack S)
{
	if(S->top == -1){
		printf("空栈\n");
		return Error; 
	}else{
		return (S->data[(S->top)--]);
	}
}

        第二种解决方法不需要建立树。因为题目给出的是非递归的中序遍历,那么其实在它的堆栈操作中,Push结点的顺序就是先序遍历的顺序,Pop结点的顺序就是中序遍历的顺序,那么我们就可以根据先序和中序遍历的顺序通过递归求解“左右子树”后序遍历顺序的方式求出后序遍历的顺序。

具体代码实现为:

#include<stdio.h>
#include<stdlib.h> 
#include<string.h>

#define ElementType int
#define MaxN 35

typedef struct SNode *Stack;
struct SNode{
	ElementType *data;
	int top;
	int MaxSize; 
};

int pre[MaxN],in[MaxN],post[MaxN];  //存储先序、中序、后序遍历的数组 

Stack CreateStack(int MaxSize); 
void Push(Stack PtrS,ElementType X);
ElementType Pop(Stack PtrS);
void Post_solve(int preL,int inL,int postL,int n); 

int main()
{
	int i,j=0,k=0,x,N;
	int first = 1;
	char str[10];
	
	scanf("%d",&N);
	Stack s = CreateStack(N);
	for(int i=0; i<2*N; i++){
		scanf("%s",str);
		if(strcmp(str,"Push") == 0){
			scanf("%d",&x);
			pre[j++] = x;
			Push(s,x);
		}else{
			in[k++] = Pop(s);
		}
	}
	Post_solve(0,0,0,N);
	for(i=0; i<N; i++){
		if( first ){
			first = 0;
			printf("%d",post[i]);
		}else{
			printf(" %d",post[i]);
		}
	}
	
	return 0;
}

void Post_solve(int preL,int inL,int postL,int n)   
{/*preL,inL,postL分别表示当前遍历数组的最左端*/
	int i,root;
	int Left,Right;
	
	if( n == 0 )  return;  //当递归至只有没有数时,直接返回 
	if( n == 1 ){
		post[postL] = pre[preL];  //当递归至只有一个数时,先序,中序,后序的数组里面的值是相等的 
		return;
	}
	root = pre[preL];  //当前树的根结点肯定是先序遍历的第一个结点 
	post[postL+n-1] = root;  //在后序遍历中,当前树的根结点肯定是最后访问的 
	for(i=0; i<n; i++){/*在中序遍历中找到当前树的根结点*/
		if( in[inL+i] == root )  break; 
	}
	Left = i;  //当前树的左子树所包含的结点数 
	Right = n-Left-1;  //当前树的右子树所包含的结点数
	Post_solve(preL+1,inL,postL,Left);  //递归解决左子树的后序遍历
	Post_solve(preL+Left+1,inL+Left+1,postL+Left,Right);  //递归解决右子树的后序遍历
}

//建立空栈 
Stack CreateStack(int MaxSize)
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
    S->top = -1;
    S->MaxSize = MaxSize;
    
    return S;
}
//入栈
void Push(Stack S,ElementType X)
{
	if(S->top == S->MaxSize-1)
	    printf("堆栈满\n");  
	else
	    S->data[++(S->top)] = X;
 } 
//出栈
#define Error -1
ElementType Pop(Stack S)
{
	if(S->top == -1){
		printf("空栈\n");
		return Error; 
	}else{
		return (S->data[(S->top)--]);
	}
}

 

7-5 Tree Traversals Again (25 分) 7-5 Tree Traversals Again (25 分) 这道题给出的是利用Stack来进行中序遍历的操作,让我们根据操作来得到后序遍历的结果。 我的思路是根据题目给出的操作,反向建立二叉树。 最后后序遍历得到答案。 AC代码: #include <stdio.h> #include <stdlib.h> #include <string.h> type... 阅读详情

相关推荐

03-树2. Tree Traversals Again.zip

给你inorder的栈操作步骤,让你写出postorder后的序列。 http://blog.youkuaiyun.com/xkzju2010/article/details/46325457

7-10 Tree Traversals Again(二叉树)

题目链接:点击打开链接7-10 Tree Traversals Again(25 分)An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys n...

z2664836046的博客 1391

输入一个华氏温度,要求输出摄氏温度。公式为 c=5(F-32)/9 输出要求有文字说明,取位2小数。

输入一个华氏温度,要求输出摄氏温度。公式为 c=5(F-32)/9 输出要求有文字说明,取位2小数。

7-5 Tree Traversals Again (25 分)

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stac...

CodeMonkey 876

数据清洗(Data Cleansing)

数据清洗(Data Cleansing)是指对数据进行处理和纠错,以去除或修复数据集中存在的错误、不致、不完整和冗余的数据,从而使数据更加准确、可靠和有用。数据清洗是数据处理和数据分析中一个非常重要的步骤,它可以帮助我们提高数据的质量,从而提高数据分析和机器学习的准确性和可靠性。数据清洗是一个重要的过程,它可以帮助我们提高数据的质量,从而提高数据分析和机器学习的准确性和可靠性。在实际应用中,我们可以使用一些工具和技术来实现数据清洗,例如 Pandas、NumPy 和 OpenRefine 等。通过数据清洗,

meimei169500的博客 1万+

六维力传感器选型指南:电阻式vs电容式,哪个更适合你的工业场景?

本文深入解析六维力传感器在工业自动化中的选型要点,重点对比电阻式与电容式传感器的核心原理、环境适应性及成本结构。针对不同工业场景(如高精度装配、重载机器人等),提供专业选型建议,帮助工程师优化系统性能与经济效益。

weixin_42525005的博客 395

7-5 Tree Traversals Again

7-5 Tree Traversals Again (25 分) An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered f...

lannister_awalys_pay的博客 948

Cursor 使用教程(2025年更新版)

官方Cursor详细使用教程在“扩展学习”

我是赛博AI Lewis 7082

03-树3 Tree Traversals Again

03-树3 Tree Traversals Again(25 分)An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered fr...

Jingwang Li 438

Linux中Hadoop 集群搭建

零、下载Hadoop: http://archive.cloudera.com/cdh5/cdh/5/?tdsourcetag=s_pctim_aiomsg 一、集群规划: 搭建的 hadoop 集群由 3 台服务器组成,分别叫做 master,salve1 和 slave2。其中 master 作为主节点,slave1 和 slave2 作为从节点。 二、网络配置: 1.查看 3 个节点的主机名...

白墨的小白博客 3992

我终于停止写 JUnit 了!用 JavaParser + GPT-4 自动生成 90% 覆盖率的单元测试

本文介绍了一种基于JavaParser和GPT-4的智能单元测试生成方案。针对开发者在单元测试编写中面临的繁琐、无聊和硬指标等问题,提出通过AST语法树分析代码结构,提取关键信息后生成精准提示词,再调用GPT-4自动生成高质量的单元测试代码。文章详细阐述了技术原理、实现步骤(包括JavaParser解析、上下文感知提示词构建和GPT-4调用),并展示了该方法能自动识别依赖、Mock对象和覆盖边界条件,显著提升测试效率。同时指出了在复杂数据结构、私有方法测试等方面的局限性,最终强调这种技术组合可以解放开发者,

BUG猿的博客 1131

[PTA] 7-5 Tree Traversals Again

题目详情 题目分析: 这道题的关键是如何重建树 由图可知,每一次push就是向下建树 每一次pop结束后一次push都是创建右子树 每一次push之后的连续push都是创建左子树 每一次push后的第一次pop都是在图中相当于拐一个弯,但cur(即当前节点的指针)所指向的节点没有变 每一次pop之后的连续pop都是向上回溯,我们每一个节点都记录它上一个节点是哪个,此外每一个节点用visit来记录是否已经被pop过了,向上回溯的时候一直要回溯到没有被pop的节点,一旦被访问就将这个节点的visit标记为1

yym68686 292

Central Finance 全景解析:用 SAP S/4HANA 构建跨系统的财务中台与渐进式转型路径

Central Finance 是基于 SAP S/4HANA 的一种部署与应用场景:在不打断现有异构源系统运营的前提下,把多套 SAP 与非 SAP 系统中的财务与管理会计数据实时/准实时复制到一套中心化的 SAP S/4HANA 中,作为统一的记账与分析底座,逐步把选定的财务流程(如预算控制、付款、固定资产结账等)迁入中心系统。这让企业既能快速获得统一报表与统一核算结构,又为未来的整体迁移留出了弹性路径。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 393

7-5-Tree Traversals Again-编程题

7-5-Tree Traversals Again-编程题解题代码测试结果问题整理 解题代码 #include<stdio.h> #include<stdlib.h> #include<string.h> int Flag = 1; typedef struct stack* pst; struct stack { int* data; int* flag;...

Aruasg的博客 182

OpenClaw人人养虾:配置通义千问(Qwen)

通义千问(Qwen)是阿里云推出的大语言模型系列。OpenClaw 支持通过 Qwen Portal 插件实现 OAuth 免费额度认证,每日可免费使用 2000 次请求,无需绑定支付方式。

王国平的博客 1258

基于Simulink的永磁同步电机三闭环(位置/速度/电流)控制仿真

本文详细介绍了基于Simulink的永磁同步电机三闭环控制系统设计与实现方法。系统采用位置环、速度环、电流环的三层嵌套结构,通过坐标变换(Clark/Park)实现解耦控制,达到精密定位目的。文章包含完整的建模步骤:从主电路搭建、三环PID设计到坐标变换与SVPWM调制实现,并提供了核心控制算法的MATLAB代码。通过工业机械臂关节场景验证,系统在阶跃响应(稳态误差0.002°)、正弦跟踪(误差0.008°)和抗扰动性能(恢复时间0.05s)方面表现优异。最后还提出了前馈补偿、扰动观测器等优化方向。该方案适

xiaoheshang_123的博客 280

PAT 7-5 Tree Traversals Again

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(

qq466546731的博客 119

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

7-5 Tree Traversals Again (25分)

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stac...

qq_46167487的博客 422

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

7-5 Tree Traversals Again (25 分)*

inorder 无序 implemented 实施 recursive 递归 unique 唯一的确定的 generated 产生 sequence 序列 operations 运行 实施 postorder traversal sequence 后序遍历序列 题意:给出中序遍历,得到后序遍历结果 观察Push的顺序为先序遍历,Pop的顺序为中序遍历,先根据其顺序建立数组先序遍历数组pre[]和中序遍历数组in[] vector<int> pre, in, post; void postor

此地无银三百两 199

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

浙大PAT:7-5 Tree Traversals Again (25分)

7-5 Tree Traversals Again (25分) An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered fro...

Yusamm的博客 403

浙大PTA 7-5 Tree Traversals Again (25point(s))

7-5 Tree Traversals Again (25point(s)) An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbe...

Steve_Liu12399的博客 257

【PTA Data Structures and Algorithms (English)】7-5 Tree Traversals Again

有一棵树,树的遍历可以用栈来实现,然后给出你这棵树用栈实现后的Push和Pop的序列,然后让你给出这棵树的后序遍历。

weixin_51979465的博客 446

PAT-ADVANCED1086/Data Structures and Algorithms7-5——Tree Traversals Again

我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED 我的Data Structures and Algorithms代码仓:https://github.com/617076674/Data-Structures-and-Algorithms 原题链接: PAT-ADVANCED1086:https://pintia.cn/...

清风阁 216

数据结构暑期自学--MOOC浙江大学pta(7-5 Tree Traversals Again)

第一次做这题,用的是根据先序和中序来建立个树,再后序遍历该树,听了课才发现,可以直接利用先序和中序来直接退出后序遍历。1、首先,不难发现,在出栈和入栈的过程中,所有的push操作,都是在先序遍历题目输入:那么该样例的先序遍历即为所有的pop出的数为该数的中序遍历2、接下来就利用这两种数据来推出后序遍历首先先序遍历的第一个点即为根节点,即为后序遍历的最后一个数接下来是在中序遍历中找该根节点,通过这个过程来确定左子树的个数,进而求出右子树的个数再进行这样的不断递归 3、用栈来模拟样例中的操作,来求出先序和中

m0_60531106的博客 208

03-树3 Tree Traversals Again (c++递归实现)

题目 An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the s...

Sicilly的博客 359
上一篇: 7-4 List Leaves
下一篇: 7-6 Root of AVL Tree
弱爆了的雪饼
博客等级 码龄10年 76粉丝 70原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值