深度优先与广度优先遍历二叉树

在这里插入图片描述
对于一颗二叉树,深度优先搜索(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;
}


过程见图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41568105/article/details/84452011