C++根据前序遍历和后序遍历建二叉树

    xiaoxiao2021-03-25  183

    #include<bits/stdc++.h> using namespace std; class Node{ public: Node* left; Node* right; char content; Node(){ left=NULL; right=NULL; } }; void postOrder(Node* T){ if(T!=NULL){ if(T->left!=NULL) postOrder(T->left); if(T->right!=NULL) postOrder(T->right); printf("%c",T->content); } } char pre[30],in[30]; Node* build(int p_start,int p_end,int in_start,int in_end){ Node* ret=new Node[1]; ret->content=pre[p_start]; int rootIdx; for(int i=in_start;i<=in_end;i++){ if(in[i]==pre[p_start]){ rootIdx=i; break; } } if(rootIdx!=in_start) ret->left=build(p_start+1,p_start+(rootIdx-in_start),in_start,rootIdx-1); if(rootIdx!=in_end) ret->right=build(p_start+1+(rootIdx-in_start),p_end,rootIdx+1,in_end); return ret; } int main(){ int num; int val,temp1,temp2; while(scanf("%s",pre)!=EOF){ scanf("%s",in); int len1=strlen(pre); Node* T=build(0,len1-1,0,len1-1); postOrder(T); printf("\n"); } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1700.html

    最新回复(0)