二叉樹演算法:中序、後序推導先序(數組遞迴實現)

來源:互聯網
上載者:User

標籤:

中根序列和後根序列重建二叉樹
描述

我們知道如何按照三種深度優先次序來周遊一棵二叉樹,來得到中根序列、前根序列和後根序列。反過來,如果給定二叉樹的中根序列和後根序 列,或者給定中根序列和前根序列,可以重建一二叉樹。本題輸入一棵二叉樹的中根序列和後根序列,要求在記憶體中重建二叉樹,最後輸出這棵二叉樹的前根序列。

用不同的整數來唯一標識二叉樹的每一個結點,下面的二叉樹

中根序列是9 5 32 67

後根序列9 32 67 5

前根序列5 9 67 32

先讀入一個數n代表中序和後序均有n個元素。

接著輸入中序序列,在輸入後序序列。

輸出先序序列。

輸入:

4

9 5 32 67

9 32 67 5

輸出:

5 9 67 32

#include <stdio.h>#include <string.h>void build(int len, int *s1, int *s2, int *s){    int p;    int i;    if(len<=0)        return;    else{        for(i=0; i<len; i++){            if(s1[i]==s2[len-1]){                p = i;            }        }        build(p, s1, s2, s+1);        build(len-p-1, s1+p+1, s2+p, s+p+1);        s[0] = s2[len-1];    }}int main(){    int i;    int s1[1000], s2[1000], s3[1000];    int n;    while(scanf("%d", &n)!=EOF)    {        for(i=0; i<n; i++){            scanf("%d", &s1[i] );        }        for(i=0; i<n; i++){            scanf("%d", &s2[i] );        }        build(n, s1, s2, s3 );        for(i=0; i<n; i++){            printf("%d%c", s3[i], i==n-1?‘\n‘:‘ ‘ );        }    }    return 0;}

 

二叉樹演算法:中序、後序推導先序(數組遞迴實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.