标签:个数 amp tor name mes next nod tree 映射
建立二叉树(链式存储)
一、给定后序和中序数列,建立二叉树
1 #include<iostream> 2 #include<vector> 3 #include<unordered_map> 4 using namespace std; 5 typedef struct node* BT; 6 struct node{ 7 int data; 8 BT left=NULL,right=NULL; 9 }; 10 11 vector<int> Post,In;//存储后序遍历和中序遍历的元素 12 unordered_map<int,int> mp;//映射中序数组和下标的关系 13 14 BT BuildTree(int PostIndex,int InLeft,int InRight); 15 void Postorder(BT t);//后序遍历输出,用于检测正确性 16 17 int main(void) 18 { 19 int N; 20 scanf("%d",&N); 21 Post.resize(N+1); 22 In.resize(N+1); 23 for(int i=1;i<=N;i++) 24 scanf("%d",&Post[i]); 25 for(int i=1;i<=N;i++){ 26 scanf("%d",&In[i]); 27 mp[In[i]]=i; 28 } 29 BT tree=NULL; 30 tree=BuildTree(N,1,N); 31 Postorder(tree); 32 return 0; 33 } 34 35 void Postorder(BT t) 36 { 37 if(t!=NULL){ 38 Postorder(t->left); 39 Postorder(t->right); 40 printf("%d ",t->data); 41 } 42 } 43 44 BT BuildTree(int PostIndex,int InLeft,int InRight) 45 { 46 if(InLeft>InRight) return NULL; 47 BT t=new node(); 48 t->data=Post[PostIndex]; 49 t->right=BuildTree(PostIndex-1,mp[Post[PostIndex]]+1,InRight); 50 int next=PostIndex-InRight+mp[Post[PostIndex]]-1;//下一个元素在Post中的位置即当前节点的PostIndex减去它的右子树的元素个数再-1 51 t->left=BuildTree(next,InLeft,mp[Post[PostIndex]]-1); 52 return t; 53 }
二、给定先序和中序数列,建立二叉树
#include<iostream> #include<vector> #include<unordered_map> using namespace std; typedef struct node *BT; struct node{ int data; BT left=NULL,right=NULL; }; vector<int> Pre,In; unordered_map<int,int> mp; void Preorder(BT t); BT BuildTree(int PreIndex,int InLeft,int InRight); int main(void) { int N; scanf("%d",&N); Pre.resize(N+1); In.resize(N+1); for(int i=1;i<=N;i++) scanf("%d",&Pre[i]); for(int i=1;i<=N;i++){ scanf("%d",&In[i]); mp[In[i]]=i; } BT tree=BuildTree(1,1,N); Preorder(tree); return 0; } void Preorder(BT t) { if(t!=NULL){ printf("%d ",t->data); Preorder(t->left); Preorder(t->right); } } BT BuildTree(int PreIndex,int InLeft,int InRight) { if(InLeft>InRight) return NULL; BT t=new node(); t->data=Pre[PreIndex]; t->left=BuildTree(PreIndex+1,InLeft,mp[Pre[PreIndex]]-1); int next=PreIndex+mp[Pre[PreIndex]]-InLeft+1; t->right=BuildTree(next,mp[Pre[PreIndex]]+1,InRight); return t; }
标签:个数 amp tor name mes next nod tree 映射
原文地址:https://www.cnblogs.com/yinhao-ing/p/10504965.html