C 資料結構 二叉樹操作

2021-07-27 10:59:15 字數 1559 閱讀 3644

基本知識點不講了,直接說遍歷問題:

前序遍歷:根節點->左子樹->右子樹

中序遍歷:左子樹->根節點->右子樹

後序遍歷:左子樹->右子樹->根節點

具體看**【未完待續,困,明天繼續】

//  binarytreetest.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include #include using namespace std;

// 定義二叉樹接點資料型別

typedef char datatype;

// 定義二叉樹結點

typedef struct binnode

*pbinnode, *bintree;

// 遞迴實現

void createbintree(bintree &t)

else }

// 前序遍歷

void preorder(bintree t)

}// 中序遍歷

void inorder(bintree t)

}// 後序遍歷

void posorder(bintree t)

}// 非遞迴實現,需要結合堆疊實現

// 前序遍歷

/* 對於任一結點p:

1)訪問結點p,並將結點p入棧;

2)判斷結點p的左孩子是否為空,

若不為空,輸出當前結點值,當前結點指標入棧,左孩子置為當前的結點p;

若為空,取棧頂結點,棧頂結點的右孩子為當前的結點p;

3)直到p為null並且棧為空,則遍歷結束。

*/void preordernonrecursive(bintree t)

stackstacknodes;

pbinnode node = t;

while (node != null || !stacknodes.empty())

if (!stacknodes.empty())

}}// 中序遍歷

/* 對於任一結點p:

1)當前非空結點入棧,結點左孩子賦值為當前結點,直到結點為空

2)取棧頂元素並進行出棧操作,訪問該棧頂結點值,結點右孩子賦值為當前結點;

3)直到p為null並且棧為空則遍歷結束

*/void inordernonrecursive(bintree t)

stackstacknodes;

pbinnode node = t;

while (node != null || !stacknodes.empty())

if (!stacknodes.empty())

}}// 後序遍歷

/**/

void posordernonrecursive(bintree t)

stackstacknodes;

pbinnode node = t;

while (node != null || !stacknodes.empty()) }

int _tmain(int argc, _tchar* argv)

C 資料結構(樹 二叉樹)

樹的定義 樹是你 n 0 個節點的有限集t t為空是空樹 非空樹具有兩個條件。有且僅有乙個根節點作為樹根 其餘節點可分為m個互不相交的子集t1,tm。其中每乙個子集本手又是一顆樹,稱其為跟節點的子樹。遞迴思想 樹的二元組表示 t d,r d 樹t中的節點集合,r 樹中的節點關係。二元組另外一種表示 ...

資料結構 二叉樹 反轉二叉樹

include using namespace std define maxsize 1000 struct binary tree node class queue queue queue void queue push binary tree node btn binary tree node ...

《資料結構》 二叉樹

二叉樹 是 n個結點的有限集,它或為空集,或由乙個根結點及兩棵互不相交的 分別稱為該根的左子樹和右子樹的二叉樹組成。二叉樹不是樹的特殊情況,這是兩種不同的資料結構 它與無序樹和度為 2的有序樹不同。二叉樹的性質 1 二叉樹第 i層上的結點數最多為 2 i 1 2 深度為 k的二叉樹至多有 2 k 1...