1. 程式人生 > >深度優先與廣度優先遍歷二叉樹

深度優先與廣度優先遍歷二叉樹

在這裡插入圖片描述
對於一顆二叉樹,深度優先搜尋(Depth First Search)是沿著樹的深度遍歷樹的節點,儘可能深的搜尋樹的分支。以上面二叉樹為例,深度優先搜尋的順序為:ABDECFG。怎麼實現這個順序呢 ?深度優先搜尋二叉樹是先訪問根結點,然後遍歷左子樹接著是遍歷右子樹,因此我們可以利用堆疊的先進後出的特點,
先將右子樹壓棧,再將左子樹壓棧,這樣左子樹就位於棧頂,可以保證結點的左子樹先與右子樹被遍歷。
廣度優先搜尋(Breadth First Search),又叫寬度優先搜尋或橫向優先搜尋,是從根結點開始沿著樹的寬度搜索遍歷,上面二叉樹的遍歷順序為:ABCDEFG。可以利用佇列實現廣度優先搜尋。

深度優先廣度優先遍歷二叉樹程式碼

//
//  dfsbfstree.hpp
//  dfs bfs
//
//  Created by zhan_even on 2018/11/24.
//  Copyright © 2018年 zhan_even. All rights reserved.
//

#ifndef dfsbfstree_hpp
#define dfsbfstree_hpp

#include <iostream>
#include <stack>
#include <queue>
using namespace std;

int trindex = 0;

typedef struct Node {
    char data;
    struct Node *lchild;
    struct Node *rchild;
} *Tree;

//二叉樹構造器,按先序遍歷順序構造二叉樹
//無左子樹或右子樹用'#'表示
void treeNodeConstructor(Tree &root, char data[]){
    char e = data[trindex++];
    if(e == '#'){
        root = NULL;
    }
    else{
        root = (Node *)malloc(sizeof(Node));
        root -> data = e;
        treeNodeConstructor(root->lchild, data);  //遞迴構建左子樹
        treeNodeConstructor(root->rchild, data);  //遞迴構建右子樹
    }
}
//深度優先 棧先進後出
void dfs(Tree root){
    stack<Node *> nodeStack;
    nodeStack.push(root);
    Node *node;
    while (!nodeStack.empty()) {
        node = nodeStack.top(); //根結點
        printf("%c", node -> data);
        nodeStack.pop();
        if (node -> rchild) {
            nodeStack.push(node -> rchild); //先將右子樹壓棧
        }
        if (node -> lchild) {
            nodeStack.push(node -> lchild); //再將左子樹壓棧
        }
    }
}
//廣度優先,佇列先進先出
void bfs(Tree root){
    queue<Node *> nodeQueue;
    nodeQueue.push(root);
    Node *node;
    while (!nodeQueue.empty()) {
        node = nodeQueue.front();
        nodeQueue.pop();
        printf("%c", node->data);
        if(node->lchild){
            nodeQueue.push(node->lchild);  //先將左子樹入隊
        }
        if(node->rchild){
            nodeQueue.push(node->rchild);  //再將右子樹入隊
        }
    }
}


#endif /* dfsbfstree_hpp */

呼叫:

//
//  dfsTree.cpp
//  dfs bfs
//
//  Created by zhan_even on 2018/11/24.
//  Copyright © 2018年 zhan_even. All rights reserved.
//

#include "dfsbfstree.hpp"
int main(){
    //上圖所示的二叉樹先序遍歷序列,其中用'#'表示結點無左子樹或無右子樹
    char data[15] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F','#', '#', 'G', '#', '#'};
    Tree tree;
    treeNodeConstructor(tree, data);
    printf("深度優先遍歷二叉樹結果: \n");
    dfs(tree);
    cout << endl;
    printf("廣度優先遍歷二叉樹結果: \n");
    bfs(tree);
    cout << endl;
    return 0;
}


過程見圖
在這裡插入圖片描述