由遍歷序列構造二叉樹

2021-07-15 22:58:27 字數 1737 閱讀 4528

由二叉樹的先序+中序、後序+中序、層次+中序都可以唯一的確定一棵二叉樹。需要注意的是,如果只知道二叉樹的先序序列和後序序列是無法唯一確定一棵二叉樹的。

題意:輸入某二叉樹的先序遍歷和中序遍歷結果,請重建出該二叉樹,並輸出它的後序遍歷序列。

解題思路:在二叉樹的先序遍歷中,第乙個數字是根結點,在中序遍歷中,根結點在序列的中間,左子樹在根結點的左邊,右子樹在根結點的右邊。因此可以通過掃瞄中序序列,找到根結點,可以得到左子樹及其右子樹的結點集,也即得到了左、右子樹的先序遍歷序列和中序遍歷序列,利用遞迴的方法來完成。**如下:

//由遍歷序列構造二叉樹

//輸入某二叉樹的先序遍歷和中序遍歷的結果,請重建出該二叉樹。

//假設輸入的先序遍歷和終序遍歷的結果中都不含重複的數字。#includeusing namespace std;

typedef struct bitreenode*bitree;

//函式宣告

bitreenode* construct(int *preorder, int *inorder, int length);

bitreenode* constructcore(int *startpreorder,int *endpreorder,int *startinorder,int *endinorder);

void postorderprint(bitreenode *root);

void main()

; int i=;

int *pre=p;//先序序列

int *in=i;//中序序列

int length=8;

bitreenode *root=construct(pre,in,length);

cout<<"construct success!"root->lchild=null;

root->rchild=null;

//遞迴終止條件:先序遍歷中只有乙個結點

if(startpreorder==endpreorder)

return root;

//在中序遍歷中找到根結點

int *rootinorder=startinorder;

while(rootinorder<=endinorder&&(*rootinorder)!=root->data)

rootinorder++;

if(*rootinorder!=root->data)//非法輸入!

exit(0);

int leftlength=rootinorder-startinorder;//左子樹的結點數

if(leftlength>0)//左子樹不為空,構造左子樹

root->lchild=constructcore(startpreorder+1,startpreorder+leftlength,startinorder,rootinorder-1);

int rightlength=endinorder-rootinorder;//右子樹的結點數

if(rightlength>0)//右子樹不為空,構造右子樹

root->rchild=constructcore(endpreorder-rightlength+1,endpreorder,rootinorder+1,endinorder);

return root;

}//以後序序列輸出

void postorderprint(bitreenode *root)

由遍歷序列構造二叉樹

根據前序中序確定二叉樹 根據後序中序確定二叉樹 根據層次中序確定二叉樹 注意,根據前序和後序無法確定一棵二叉樹 include include include include include include using namespace std define elemtype char typed...

由遍歷序列構造二叉樹

include include include using namespace std define maxsize 100 define maxwidth 40typedef char elemtype typedef struct node btnode btnode createbt1 cha...

二叉樹 根據二叉樹遍歷序列構造二叉樹

二叉樹的節點型別宣告如下 struct btnode 定理1任何 n 0 個不同節點的二叉樹,都可由它的前序序列和中序序列唯一地確定。根據前序遍歷的特點,知前序序列 presequence 的首個元素 presequence 0 為二叉樹的根 root 然後在中序序列 insequence 中查詢此...