資料結構與演算法 二叉樹的非遞迴遍歷

2021-09-19 10:06:40 字數 2821 閱讀 7327

基礎概念:二叉樹的非遞迴遍歷是通過棧來實現的,通過使用棧儲存節點資訊,實現非遞迴的遍歷二叉樹。

/**

**二叉樹非遞迴實現

****/

#define maxsize 100

#define increment 50

#include#include// 二叉樹的定義

typedef struct treenodetreenode,*tree;

// 棧的定義

typedef struct stackstack;

// 佇列的定義

typedef struct queuequeue;

/******************* 二叉樹 函式宣告 ********************/

void createtree(tree &t); // 建立二叉樹

void perorder(tree t); // 先序遍歷二叉樹

void inorder(tree t); // 中序遍歷二叉樹

void postorder(tree t); // 後序遍歷二叉樹

void levelorder(tree t); // 層次遍歷二叉樹

/******************* 二叉樹 函式宣告 ********************/

/******************* 棧 函式宣告 ********************/

void initstack(stack &s); // 初始化棧

void push(stack &s,tree t); // 入棧

void pop(stack &s,tree &t); // 出棧

int ifstack(stack s); // 判斷是否為空棧,為空返回1,不空返回0

void gettopelement(stack s,tree &t);// 獲取棧頂元素

/******************* 棧 函式宣告 ********************/

/******************* 佇列 函式宣告 ********************/

void initqueue(queue &q); // 初始化佇列

void enqueue(queue &q,tree t); // 入隊

void outqueue(queue &q,tree &t); // 出隊

int ifqueue(queue q); // 判斷是否為空佇列,為空返回1,不空返回0

/******************* 佇列 函式宣告 ********************/

void main()

/******************* 二叉樹 函式實現 ********************/

// 建立二叉樹

void createtree(tree &t)else }

// 先序遍歷二叉樹

void perorder(tree t)else }}

// 中序遍歷二叉樹

void inorder(tree t)else }}

// 後序遍歷二叉樹

void postorder(tree t)else

if(temp->left != null)

} }}// 層次遍歷二叉樹

void levelorder(tree t)

if(temp->right != null) }}

/******************* 二叉樹 函式實現 ********************/

/******************* 棧 函式實現 ********************/

// 初始化棧

void initstack(stack &s)

s.top = s.base;

s.nowsize = maxsize;

}// 入棧

void push(stack &s,tree t)

s.nowsize += increment;

s.top = s.base + s.nowsize;

} *s.top++ = t;

}// 出棧

void pop(stack &s,tree &t)

t = *(--s.top);

}// 判斷是否為空棧,為空返回1,不空返回0

int ifstack(stack s)

return 0;

}// 獲取棧頂元素

void gettopelement(stack s,tree &t)

t = *(s.top-1);

}/******************* 棧 函式實現 ********************/

/******************* 佇列 函式實現 ********************/

// 初始化佇列

void initqueue(queue &q)

q.front = q.rear = q.base;

}// 入隊

void enqueue(queue &q,tree t)

// 出隊

void outqueue(queue &q,tree &t)

t = *q.front++;

} // 判斷是否為空佇列,為空返回1,不空返回0

int ifqueue(queue q)

return 0;

}/******************* 佇列 函式實現 ********************/

資料結構 二叉樹遍歷 非遞迴演算法

二叉樹的遍歷非遞迴演算法。include include define maxsize 100 typedef char elemtype using namespace std typedef struct node btnode void createbtnode btnode b,char s...

資料結構 18 二叉樹(非遞迴)

二叉樹 使用非遞迴方法,建立樹 前中後序及層級遍歷樹。建立樹時,按照左子樹小於樹根,右子樹大於樹根,這樣中序遍歷就是有序表 include include 層級遍歷時,用到了queue模板類 include 前中後遍歷時,用到了stack模板類 using namespace std class n...

資料結構 二叉樹的遞迴 非遞迴遍歷

複習一下二叉樹遞迴非遞迴的先中後序遍歷 寫非遞迴後序遍歷的時候卡殼了,參考了一下網上的思路,大概有兩種,一種是標記每個節點是否有走過,如果父節點的左右子節點都標記訪問過,則可以訪問父節點 一種是定義乙個指標,指向上乙個訪問的節點,如果某父節點的右子節點為null或者是上乙個訪問的節點,則該父節點應當...