由兩種遍歷序列確定二叉樹

2021-09-29 04:21:37 字數 2772 閱讀 8873

已知中序和後序遍歷

typedef

int elemtype;

typedef

struct tnode *position;

typedef position bintree;

typedef

struct tnode

;bintree creat

(int

*a,int

*b,int n)

//陣列a,b分別存放中序,後序遍歷結果

} bt-

>lchild =

creat

(a,b,q)

; bt-

>rchild =

creat

(a+q+

1,b+q,n-q-1)

;return bt;

}

7-35 根據後序和中序遍歷輸出先序遍歷 (25 分)

本題要求根據給定的一棵二叉樹的後序遍歷和中序遍歷結果,輸出該樹的先序遍歷結果。

輸入格式:

第一行給出正整數n(≤30),是樹中結點的個數。隨後兩行,每行給出n個整數,分別對應後序遍歷和中序遍歷結果,數字間以空格分隔。題目保證輸入正確對應一棵二叉樹。

輸出格式:

在一行中輸出preorder:以及該樹的先序遍歷結果。數字間有1個空格,行末不得有多餘空格。

輸入樣例:

72 3 1 5 7 6 4

1 2 3 4 5 6 7

輸出樣例:

preorder: 4 1 3 2 6 5 7

#include

#include

#include

const

int maxn =

100;

typedef

int elemtype;

typedef

struct tnode *position;

typedef position bintree;

typedef

struct tnode

;int p[maxn]

,q[maxn]

;bintree creat

(int

*a,int

*b,int n)

} bt-

>lchild =

creat

(a,b,q)

; bt-

>rchild =

creat

(a+q+

1,b+q,n-q-1)

;return bt;

}void

preorder

(bintree t)

}int

main

(void

)

已知 前序和中序遍歷

typedef

char elemtype;

typedef

struct tnode *position;

typedef position bintree;

typedef

struct tnode

;bintree creat

(char

*a,char

*b,int n)

} bt-

>lchild =

creat

(a+1

,b,q)

; bt-

>rchild =

creat

(a+q+

1,b+q+

1,n-q-1)

;return bt;

}

7-36 還原二叉樹 (25 分)

給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。

輸入格式:

輸入首先給出正整數n(≤50),為樹中結點總數。下面兩行先後給出先序和中序遍歷序列,均是長度為n的不包含重複英文本母(區別大小寫)的字串。

輸出格式:

輸出為乙個整數,即該二叉樹的高度。

輸入樣例:

9abdfghiec

fdhgibeac

輸出樣例:

5

#include

#include

#include

const

int maxn =

100;

typedef

char elemtype;

typedef

struct tnode *position;

typedef position bintree;

typedef

struct tnode

;char p[maxn]

,q[maxn]

;bintree creat

(char

*a,char

*b,int n)

} bt-

>lchild =

creat

(a+1

,b,q)

; bt-

>rchild =

creat

(a+q+

1,b+q+

1,n-q-1)

;return bt;

}int

getheight

(bintree t)

else

return0;

}int

main

(void

)

6 7由遍歷序列確定的二叉樹

在二叉樹的遍歷中,我們知道,給定一棵二叉樹和一種遍歷方法,就可以確定該二叉樹相應的線性序列。那麼,根據給定的遍歷序列能否唯一的確定一棵二叉樹呢?顯然,只由一種序列是無法確定二叉樹的,要根據遍歷序列確定二叉樹,至少需要知道該二叉樹的兩種遍歷序列。表 6 1 列出了兩種遍歷序列組合確定二叉樹的情況。例已...

由遍歷序列確定二叉樹 資料結構

由二又樹的遍歷可知,任意一棵二又樹的先序 中序 後序遍歷序列均是唯一的。由先序和中序序列,或由中序和後序序列,均可以唯一確定一棵二叉樹。注意 由先序和後序無法確定一顆二叉樹 1.由先序和中序序列確定二叉樹 根據二叉樹遍歷的定義可知,二叉樹的先序遍歷是先訪問根結點d,其次遍歷左子樹l,最後遍歷右子樹r...

根據遍歷序列確定二叉樹

1.在先序序列中,第乙個結點一定是二叉樹的根結點 2.在中序序列中,根結點必然將中序序列分割成兩個子串行 前乙個子串行是根結點的左子樹的中序序列,後乙個是右子樹的 3.根據這兩個子串行,在先序序列中找到對應的左右子串行 4.在先序序列中,左子串行的第乙個結點是左子樹的根結點,右子串行同理 5.如此遞...