1020. Tree Traversals

来源:互联网 发布:阿里巴巴 淘宝便宜 编辑:程序博客网 时间:2024/05/17 15:56

题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1020

二叉树建立、层次遍历

// 层次遍历// 递归建立二叉树// vector/queue#include <stdio.h>#include <iostream>#include <queue>#include <vector>using namespace std;struct Tree{int key;Tree* left;Tree* right;};vector<int> level_order_buf;queue<Tree*> q;Tree *CreatTree(int in[], int post[], int n){if(n <= 0){return NULL;}Tree *root = (Tree *)malloc(sizeof(Tree));root->key = post[n-1];root->left=NULL;root->right=NULL;int i;for(i=0;i<n; i++){if(in[i] == post[n-1])break;}root->left=CreatTree(in, post, i);root->right=CreatTree(in+i+1, post+i, n-i-1);return root;}int levelOrder(Tree *root){while(q.empty() == false){q.pop();}if(root != NULL){q.push(root);}while(q.empty() == false){Tree *node = q.front();q.pop();level_order_buf.push_back(node->key);if(node->left != NULL){q.push(node->left);}if(node->right != NULL){q.push(node->right);}}return 0;}int main(){#ifdef ONLINE_JUDGE#elsefreopen("E:\\in.txt", "r", stdin);//freopen("E:\\out.txt", "w", stdout);#endifint n;int i;int post[100], in[100];scanf("%d", &n);for(i=0;i<n;i++){scanf("%d", &post[i]);}for(i=0;i<n;i++){scanf("%d", &in[i]);}Tree *root = CreatTree(in, post, n);levelOrder(root);for(i=0;i<level_order_buf.size()-1;i++){printf("%d ", level_order_buf[i]);}printf("%d\n", level_order_buf[i]);return 0;}


0 0
原创粉丝点击