博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT 1020
阅读量:6870 次
发布时间:2019-06-26

本文共 2537 字,大约阅读时间需要 8 分钟。

1020. Tree Traversals (25)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
72 3 1 5 7 6 41 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2 这题也不难,由后序跟中序序列构建一颗树,然后以层次遍历的方法输出各节点数据,主要输出后要把树给销毁,不然会造成内存泄露。 代码
1 #include 
2 #include
3 4 typedef struct Node{ 5 int data; 6 struct Node *left,*right; 7 }Node; 8 int postOrder[30]; 9 int inOrder[30];10 Node* buildTree(int,int,int,int);11 void printAndDestroyTree(Node *);12 int main()13 {14 int N,i;15 while(scanf("%d",&N) != EOF){16 for(i=0;i
data = postOrder[postStart];33 p->left = p->right = NULL;34 return p;35 }36 else{37 Node *p = (Node *)malloc(sizeof(Node));38 p->data = postOrder[postEnd];39 p->left = p->right = NULL;40 int i = inStart;41 while(i<=inEnd && postOrder[postEnd] != inOrder[i++]);42 if(i > inStart+1)43 p->left = buildTree(postStart,postStart+i-inStart-2,inStart,i-2);44 if(i <= inEnd)45 p->right = buildTree(postStart+i-inStart-1,postEnd-1,i,inEnd);46 return p;47 }48 }49 50 void printAndDestroyTree(Node *p)51 {52 if(!p)53 return;54 Node *nodeArray[30];55 int top=0,base=0;56 Node *q;57 nodeArray[top++] = p;58 while(top>base){59 q = nodeArray[base++];60 if(base == 1)61 printf("%d",q->data);62 else63 printf(" %d",q->data);64 if(q->left)65 nodeArray[top++] = q->left;66 if(q->right)67 nodeArray[top++] = q->right;68 free(q);69 }70 printf("\n");71 }

 

posted on
2014-02-24 21:45 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/boostable/p/pat_1020.html

你可能感兴趣的文章
ssh 问题
查看>>
Android源代码下载编译
查看>>
nhmicro添加信审功能
查看>>
eclipse安装maven插件-解决requires ‘bundle org.slf4j.api
查看>>
jsp---语句对象Statement
查看>>
java进阶之路
查看>>
优化Android Studio
查看>>
zabbix二次开发-flask-获取告警
查看>>
我的友情链接
查看>>
java实现MD5加密处理
查看>>
实用JVM参数总结
查看>>
oracle 11g R2 64位 安装详细步骤
查看>>
Jpeg 库的解码OpenCL优化
查看>>
正则表达式
查看>>
『中级篇』docker之虚拟机创建vagrant技巧(番外篇)(81)
查看>>
交换机SPAN功能配置
查看>>
MySQL 架构组成—存储引擎
查看>>
基于数值分析思想对多项式求值的原理和应用进行探究
查看>>
vue-devtools vue开发调试神器
查看>>
PHP扩展模块的安装
查看>>