1020. Tree Traversals (25)

来源:互联网 发布:淘宝直通车图片优化 编辑:程序博客网 时间:2024/06/07 14:29

二叉树的建立及遍历

链式

照着算法笔记抄录一份

#include<iostream>#include<string>#include<queue>#include<algorithm>using namespace std;const int MAX = 30;struct node{int data;node* lchild;node* rchild;};int in[MAX],post[MAX];int n;//递归建树 node* creat(int postl,int postr,int inl,int inr){if(postl>postr){return NULL;}node* root = new node;//新建一个节点,存放当前根节点root->data=post[postr]; //在中序队列中找到后序队列的尾节点(根节点)int k;for(k=inl;k<inr;k++){if(post[postr]==in[k]) break;} int numleft = k-inl;//左子树节点数目    //返回左子树的根节点地址,赋值给root的左指针root->lchild = creat(postl,postl+numleft-1,inl,k-1);root->rchild = creat(postl+numleft,postr-1,k+1,inr);return root; }int num=0;//已输出的节点个数,用来输出空格 void BFS(node* root){queue<node*> q;//存放指针 q.push(root);while(!q.empty()){node* p = q.front();q.pop();cout<<p->data;num++;if(num<n) cout<<' ';if(p->lchild!=NULL) q.push(p->lchild);if(p->rchild!=NULL) q.push(p->rchild);}}int main(){cin>>n;for(int i=0;i<n;i++) cin>>post[i];for(int i=0;i<n;i++) cin>>in[i];node* root = creat(0,n-1,0,n-1);BFS(root);return 0; } 


0 0
原创粉丝点击