pipioj 1373: 在每个树行中找最大值

http://www.pipioj.online/problem.php?id=1373

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef int ElemType;
 4 const int N=3e5;
 5 
 6 typedef struct BiNode{
 7     ElemType data;
 8     BiNode* lchild;
 9     BiNode* rchild;     
10     BiNode(ElemType data, BiNode* lchild, BiNode* rchild) {
11         this->data = data;
12         this->lchild = lchild;
13         this->rchild = rchild;
14     }   
15 }*BiTree;
16 
17 typedef struct BiThrNode{
18     ElemType data;
19     BiThrNode* lchild;
20     BiThrNode* rchild;
21     int ltag, rtag; //tag域,表示是线索还是指向的孩子节点       
22 }*BiThrTree;
23  
24 void visit(BiNode* T) {
25     if(T!=NULL) printf("%c ", T->data );
26 }
27 
28 //先序遍历 
29 void PreOrder(BiTree T) {
30     if(T) {
31         visit(T);   // 访问根节点
32         PreOrder(T->lchild);    // 递归访问左子树
33         PreOrder(T->rchild);    // 递归访问右子树
34     }       
35 } 
36 
37 //中序遍历 
38 void InOrder(BiTree T) {
39     if(T) {
40         InOrder(T->lchild);     // 递归访问左子树
41         visit(T);   // 访问根节点
42         InOrder(T->rchild);     // 递归访问右子树
43     }       
44 } 
45 
46 //后序遍历 
47 void PostOrder(BiTree T) {
48     if(T) {
49         PostOrder(T->lchild);       // 递归访问左子树
50         PostOrder(T->rchild);   // 递归访问右子树
51         visit(T);   // 访问根节点
52     }       
53 }
54 
55 int x = 0;
56 BiTree buildtree() {
57     scanf("%d", &x);
58     if(x == -1) return NULL;
59     BiTree T = (BiTree)malloc(sizeof(BiNode));
60     T->data = x;
61     T->lchild = buildtree();
62     T->rchild = buildtree();
63     return T;
64 } 
65 
66 int ans[N],h=0;
67 
68 int treeleverlmax(BiTree T){
69     if(T){
70         queue<BiTree>q;
71         q.push(T);
72         BiTree r=T;
73         while(!q.empty()){
74             BiTree u=q.front();
75             q.pop();
76             ans[h]=max(ans[h],u->data);
77             if(u->lchild)q.push(u->lchild);
78             if(u->rchild)q.push(u->rchild);
79             if(u==r){
80                 r=q.back();
81                 h++;
82             }
83         }
84     }
85 }
86 
87 
88 int main(){
89     BiTree T=buildtree();
90     treeleverlmax(T);
91     for(int i=0;i<h;i++)printf("%d ",ans[i]);
92 }
原文地址:https://www.cnblogs.com/ccsu-kid/p/13788498.html