二叉樹的深度優先遍歷與廣度優先遍歷 [ C++ 實現 ]
阿新 • • 發佈:2019-02-19
/**
* <!--
* File : binarytree.h
* Author : fancy
* Email : [email protected]
* Date : 2013-02-03
* --!>
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <Stack>
#include <Queue>
using namespace std;
#define Element char
#define format "%c"
typedef struct
Element data;
struct Node *lchild;
struct Node *rchild;
} *Tree;
int index = 0; //全域性索引變數
//二叉樹構造器,按先序遍歷順序構造二叉樹
//無左子樹或右子樹用'#'表示void treeNodeConstructor(Tree &root, Element data[]){
Element e = data[index++];
if(e == '#'){
root = NULL;
}else{
root = (Node *)malloc(sizeof
root->data = e;
treeNodeConstructor(root->lchild, data); //遞迴構建左子樹 treeNodeConstructor(root->rchild, data); //遞迴構建右子樹 }
}
//深度優先遍歷void depthFirstSearch(Tree root){
stack<Node *> nodeStack; //使用C++的STL標準模板庫 nodeStack.push(root);
Node *node;
while
node = nodeStack.top();
printf(format, node->data); //遍歷根結點 nodeStack.pop();
if(node->rchild){
nodeStack.push(node->rchild); //先將右子樹壓棧 }
if(node->lchild){
nodeStack.push(node->lchild); //再將左子樹壓棧 }
}
}
//廣度優先遍歷void breadthFirstSearch(Tree root){
queue<Node *> nodeQueue; //使用C++的STL標準模板庫 nodeQueue.push(root);
Node *node;
while(!nodeQueue.empty()){
node = nodeQueue.front();
nodeQueue.pop();
printf(format, node->data);
if(node->lchild){
nodeQueue.push(node->lchild); //先將左子樹入隊 }
if(node->rchild){
nodeQueue.push(node->rchild); //再將右子樹入隊 }
}
}