1. 程式人生 > 實用技巧 >pipioj 1373: 在每個樹行中找最大值

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 }