C語言由後序遍歷和中序遍歷重構二叉樹練習
阿新 • • 發佈:2018-11-16
1
由中根序列和後根序列重建二叉樹(10分)
題目內容:
我們知道如何按照三種深度優先次序來周遊一棵二叉樹,來得到中根序列、前根序列和後根序列。反過來,如果給定二叉樹的中根序列和後根序列,或者給定中根序列和前根序列,可以重建一二叉樹。本題輸入一棵二叉樹的中根序列和後根序列,要求在記憶體中重建二叉樹,最後輸出這棵二叉樹的前根序列。
用不同的整數來唯一標識二叉樹的每一個結點,下面的二叉樹
中根序列是9 5 32 67
後根序列9 32 67 5
前根序列5 9 67 32
輸入格式:
兩行。第一行是二叉樹的中根序列,第二行是後根序列。每個數字表示的結點之間用空格隔開。結點數字範圍0~65535。暫不必考慮不合理的輸入資料。
輸出格式:
一行。由輸入中的中根序列和後根序列重建的二叉樹的前根序列。每個數字表示的結點之間用空格隔開。
輸入樣例:
9 5 32 67 9 32 67 5
輸出樣例:
5 9 67 32
利用遞迴的思想,先根據後續遍歷找根節點,然後遞迴建立左子數和右子數
#include <stdio.h> #include <stdlib.h> #include<iostream> using namespace std; typedef char ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode { ElementType Data; BinTree Left; BinTree Right; }; BinTree build(int n, int *mid, int *post); void PreorderPrintLeaves(BinTree BT); int main() { int mid[100]; int post[100]; int i = 0, n; char c; while (cin >> n) { mid[i++] = n; c = cin.get(); if (c == '\n') { break; } } i = 0; while (cin >> n) { post[i++] = n; c = cin.get(); if (c == '\n') break; } BinTree BT = NULL; BT = build(i, mid, post); PreorderPrintLeaves(BT); } BinTree build(int n, int *mid, int *post) { BinTree temp; if (n <= 0) return NULL; temp = (TNode *)malloc(sizeof(struct TNode)); temp->Data = post[n - 1]; temp->Left = NULL; temp->Right = NULL; int i=0; while (post[n - 1] != mid[i]) i++; temp->Left = build(i, mid, post); // 遞迴建立左子數 temp->Right = build(n - 1 - i, mid + i + 1, post + i);// 遞迴建立右子數 return temp; } int flag = 1; void PreorderPrintLeaves(BinTree BT) { if (BT == NULL) { return; } if (flag) { printf("%d", BT->Data); flag = 0; } else { printf(" %d", BT->Data); } if (BT->Left) PreorderPrintLeaves(BT->Left); if (BT->Right) PreorderPrintLeaves(BT->Right); }