二叉樹的儲存與遍歷

2021-09-28 20:29:01 字數 3019 閱讀 7150

二叉樹的儲存表示

二叉樹遍歷及其應用

結點的度:結點所擁有的子樹棵數。

結點的層次:從根到該結點所經路徑上的分支條數。

葉結點:度為0的結點。

樹的深度:樹中距離根結點最遠的結點所處層次即為樹的深度。

樹的度:樹中結點的度的最大值。

有序樹:樹中結點的各棵子樹是有次序的。

特點:每個結點最多有兩個子女,並且二叉樹的子樹有左、右之分,其子樹的次序不能顛倒,因此是有根有序樹。

適用於二叉樹的大小和形態不發生劇烈動態變化的場合,例如完全二叉樹。

二叉樹的結點至少有三個域:資料data、左子女結點指標、右子女結點指標。要找結點的父結點可以增加乙個父指標域。

l、r、v分別代表遍歷乙個結點的左子樹、右子樹和該結點。

//前序遍歷vlr

template

<

class

t>

void binarytree

::preoreder

(bintreenode

*subtree,

void

(*visit)

(bintreenode

*p))};

//中序遍歷演算法

template

<

class

t>

void binarytree

::inoreder

(bintreenode

*subtree,

void

(*visit)

(bintreenode

*p))};

//後續遍歷

template

<

class

t>

void binarytree

::postoreder

(bintreenode

*subtree,

void

(*visit)

(bintreenode

*p))

};

//前序遍歷建立二叉樹的演算法

template

<

class

t>

void binarytree

::createbintree

(ifstream& in, bintreenode

*& subtree)

createbintree

(in, subtree-

>leftchild)

;createbintree

(in, subtree-

>rightchild);}

else subtree =

null

;//建立空子樹結束遞迴}}

//以廣義表形式輸出二叉樹的演算法

#include 「binarytree.h」

template

<

class

t>

void

printbtree

(bintreenode

*bt)

}}

利用棧記錄遍歷時的回退路徑

//前序遍歷,訪問乙個結點後向左子樹遍歷下去,利用棧記錄該結點的右子女。

#include

"stack.h"

template

<

class

t>

void binarytree

::preorder

(void

(*visit)

(bintreenode

*p))

}//另一種前序遍歷的非遞迴演算法

#include

"stack.h"

template

<

class

t>

void binarytree

::preorder

(void

(*visit)

(bintreenode

*p))

}//中序遍歷非遞迴演算法

#include

"stack.h"

template

<

class

t>

void binarytree

::inorder

(void

(*visit)

(bintreenode

*p))if(

!s.isempty()

)}while

(p !=

null

||!s.

isempty()

);//結束條件是棧為空同時遍歷指標也為空,若棧為空,而指標不為空說明右子樹非空。

}//後續遍歷所用的棧的結點定義

template

<

class

t>

struct stknode

;//棧暫存根結點,當向左子樹遍歷下去,tag為l,當向右子樹遍歷為r,從右子樹退出時才訪問位於棧頂的根結點的值。

sktnode

(bintreenode

*n =

null):

ptr(n)

,tag

(l)}

後續遍歷的非遞迴演算法

#include

"stack.h"

template

<

class

t>

void binarytree

::postorder

(void

(*visit)

(bintreenode

*p))

int continue1=1;

//while

(continue1 &&

!s.isempty()

)}}while

(!s.

isempty()

):cout<}

由給定的前序序列和中序序列能夠唯一確定一棵二叉樹。

二叉樹的遍歷 二叉樹遍歷與儲存

在資料結構中,二叉樹是非常重要的結構。例如 資料庫中經常用到b 樹結構。那麼資料庫是如何去單個查詢或者範圍查詢?首先得理解二叉樹的幾種遍歷順序 先序 中序 後序 層次遍歷。先序 根節點 左子樹 右子樹 中序 左子樹 根節點 右子樹 後序 左子樹 右子樹 根節點 按層級 class node if c...

二叉樹 儲存 遍歷

樹的每個節點最多有兩個孩子節點 乙個節點編號i,它的雙親i 2,左孩子2i,右孩子2i 1 先序遍歷 根左右 中序遍歷 左根右 後續遍歷 左右根 二叉樹節點是個靜態類 private static class treenode 構建二叉樹 傳入乙個集合序列,linkedlist適合插入資料,頻繁刪除...

二叉樹的建立與遍歷 二叉樹遍歷模板)

初學二叉樹,感覺之前鍊錶掌握不熟練導致接受有點難,現在做一些總結。本題其實就是根據給出的前序遍歷 包括空子樹 寫出相應的前序 中序和後序遍歷。廢話不多說,先看看題目 description 下面給出了教材中演算法6.4所示的演算法。status createbitree bitree t retur...