二叉樹的非遞迴前序 中序 後序 層次遍歷

2021-07-10 09:46:04 字數 962 閱讀 5727

1.前序非遞迴

/*非遞迴前序遍歷*/

void preordernonrecurive(treenode *root)

cout << endl;

}

2.中序非遞迴

/*非遞迴中序遍歷*/

void inordernonrecurive(treenode *root)

if (!s.empty()) //此條件可以省略

}cout << endl;

}

注意:這種方法也適合於前序遍歷,區別是前序遍歷是在入棧的時候輸出資料,而中序遍歷是在出棧的時候輸出資料。

3.後序非遞迴

方法一:標記前乙個被訪問的結點

/*非遞迴後序遍歷*/

void postordernonrecurive(treenode *root)

cur = s.top();

if (!cur->rchild || cur->rchild == previsited)

else cur = cur->rchild;

} cout << endl;

}

方法二:雙棧法

void postordernonrecurive_(treenode *root)

while (!s2.empty())

cout << endl;

}

4.非遞迴層次遍歷

void levelorder(treenode *root)

cout << endl;

}

5.樹的深度

int depth(treenode *root)

樹 二叉樹的前序 中序 後序 層次遞迴

在二叉樹的應用中,很多使用二叉樹的操作都是通過遍歷來進行節點的修改。所以對於遍歷而言是學習二叉樹的要點,今天就來總結一下。假設二叉樹的結構為 templatestruct binarytreenode t data binarytreenode left binarytreenode right 前...

二叉樹的前序 中序 後序非遞迴遍歷 層次遍歷

一 先序遍歷 1.根節點進棧 2.節點出棧,並訪問,若有右孩子,右孩子進棧,若有左孩子,左孩子進棧 3.重複2直至棧空 01 02 09 03 06 10 13 04 05 07 08 11 12 14 15 definition for binary tree struct treenode cl...

二叉樹 非遞迴 前序 中序 後序 存檔

二叉樹 非遞迴 前中後序遍歷 其中root為空頭節點 root.left指向真實的二叉頭節點 其中前序與中序思路相同,列印節點輸出位置不同,後序要防止重複進入右節點 前序 節點入棧時立即輸出,中序 先入棧,後出棧時輸出,前序遍歷 public class dlr tmpnode stack.pop ...