码迷,mamicode.com
首页 > 其他好文 > 详细

PAT Tree Traversals Again

时间:2015-05-20 21:51:18      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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(); 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.

 

题意给出先序遍历顺序的节点 然后让你打印出后序遍历

我的方法比较老实 按照先序遍历的顺序构建一棵树  再用后序遍历输出

陈越老师的办法更巧妙  没建树 因为 push进去的是先序顺序 pop出来的是中序  然后分别递归两个顺序可的后序

我不详细介绍了 大家可以去mooc看看

下面是我的C语言代码

 1 #include "stdio.h"
 2 #include "string.h"
 3 #include "stdlib.h"
 4 typedef struct     bintre    
 5 {
 6     int data;
 7     struct bintre *left;
 8     struct bintre *right; 
 9 }BinTree;
10 int n,flag=1;
11 BinTree *CreatTree(BinTree *head);
12 void Traversal(BinTree *head); 
13 int main()
14 {
15     int i=0;
16     int a[30]={-1};
17     BinTree *head,*t;
18     
19     scanf("%d ",&n);
20     head=CreatTree(head);
21     Traversal(head);
22     printf("\n");
23 }
24 void Traversal(BinTree *head)
25 {
26     if(!head)
27         return;
28     Traversal(head->left);
29     Traversal(head->right);
30     if(flag)
31     {    
32         printf("%d",head->data);
33         flag=0;
34     }
35     else
36         printf(" %d",head->data);    
37 }
38 BinTree *CreatTree(BinTree *head)
39 {    
40     int data;
41     char flag[6];
42     if(n<=0)
43         return NULL;
44     scanf("%s",flag);
45     scanf("%d",&data);
46     
47     if(strcmp(flag,"Pop")==0)
48     {
49         head=NULL;
50         return head;
51     }
52     else 
53         n--;
54     head=(BinTree *)malloc(sizeof(BinTree ));
55     head->data=data;
56     head->left=CreatTree(head->left);
57     head->right=CreatTree(head->right);
58 
59     return head;
60     
61 }

 

PAT Tree Traversals Again

标签:

原文地址:http://www.cnblogs.com/threezj/p/4518072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!