樹的基本構造與遍曆_ACM

來源:互聯網
上載者:User

題目:1020. Tree Traversals (25)


題目描述:

已知樹的postorder(後序遍曆)與inorder(中序遍曆),構造出完整的樹,並按層次遍曆輸出數


代碼展示一(已知後與中,進行層次遍曆):

#include <iostream>#include <queue>using namespace std;const int maxn=1e3+5;int a[maxn],b[maxn];struct Tree{Tree *left,*right;int data;};Tree *buildtree(int la,int ra,int lb,int rb){if (la>ra) return NULL;int p;for (int i=lb;i<=rb;i++) if (b[i]==a[ra]) {p=i;break;}Tree *tree=new Tree;tree->data  = a[ra];tree->left  = buildtree (la,la+(p-lb)-1,lb,p-1);tree->right = buildtree (la+(p-lb),ra-1,p+1,rb);return tree;}void print_levelorder(Tree *root){queue < Tree * > q;cout<<root->data;if (root->left!=NULL)  q.push(root->left);if (root->right!=NULL) q.push(root->right);while(!q.empty()){Tree *tree=new Tree;tree=q.front();q.pop();cout<<" "<<tree->data;if (tree->left!=NULL)  q.push(tree->left);if (tree->right!=NULL) q.push(tree->right);}}int main(){//freopen("datain.txt","r",stdin);int n;cin>>n;for (int i=1;i<=n;i++) cin>>a[i];for (int i=1;i<=n;i++) cin>>b[i];Tree *root=buildtree(1,n,1,n);print_levelorder(root);}


代碼展示二(已知前與中,進行層次遍曆):

只需更改建樹的部分代碼即可

Tree *buildtree(int la,int ra,int lb,int rb){if (la>ra) return NULL;int p;for (int i=lb;i<=rb;i++) if (b[i]==a[la]) {p=i;break;}Tree *tree=new Tree;tree->data  = a[la];tree->left  = buildtree (la+1,la+(p-lb),lb,p-1);tree->right = buildtree (la+(p-lb)+1,ra,p+1,rb);return tree;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.