创建二叉树 树的深度搜索 广度搜索

来源:互联网 发布:淘宝钻展设计 编辑:程序博客网 时间:2024/06/07 19:04

树的深度搜索 与树的前序遍历同理 根节点->左孩子->右孩子  树的广度搜索 与树的层次遍历同理 一层一层遍历内容

深度搜索 采用stack的适配器 先进后出原则  而广度搜索采用的queue适配器 先进先出原则 二者正好满足 搜索需求 简要代码如下:

#include <iostream>#include <stack>#include <queue>#include <malloc.h>using namespace std;typedef struct node{    char data;    struct node* lchild;        //结构体并未定义完全 采用struct node* 类型    struct node* rchild;    node():lchild(NULL),rchild(NULL){}}*Tree;int index = 0;  //全局变量//此处采用递归创建树,传入对象为引用类型,因为在新加入的左右孩子的同时,需要保存整棵树的结构void createtree(Tree& root,char data[]){    char e = data[index++];    if(e == '#'){        root = NULL;    }else{    root = new node();    root->data = e;    createtree(root->lchild,data);  //递归创建左孩子    createtree(root->rchild,data);  //递归创建右孩子    }}void dfs(Tree root){    stack<node*> nodestack;    nodestack.push(root);    node* node;    while(!nodestack.empty()){        node = nodestack.top();        cout<<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();        cout<<node->data<<" ";        if(node->lchild){            nodequeue.push(node->lchild);        }        if(node->rchild){            nodequeue.push(node->rchild);        }    }}int main(){    char data[15] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F','#', '#', 'G', '#', '#'};    Tree tree;    createtree(tree,data);    cout<<"dfs"<<":"<<endl;    dfs(tree);    cout<<endl;    cout<<"bfs"<<":"<<endl;    bfs(tree);    return 0;}

以上创建树的递归过程如下图分析:


只给出了一半树创建的过程,另一半创建的过程 与其一致。

最后创建完成树的图像即:



而本测试小例,产生的结果如下:


简单阐述了 树的深度,广度搜索。

0 0
原创粉丝点击