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

Code

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#include <stack>
#include <queue>

using namespace std;

typedef struct BinaryTree 
{
    int val;
    struct BinaryTree *Lchild;
    struct BinaryTree *Rchild;
} binaryTree;

static int idx = 0;
// '#' representative no Lchild or Rchild.
char list[] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F','#', '#', 'G', '#', '#'};

void depthSearch(binaryTree *root)
{
    if(NULL == root) return ;
    stack<binaryTree*> myStack;
    myStack.push(root);
    binaryTree* node;
    while(!myStack.empty()){
        node = myStack.top();
        printf("%c\t", node->val);
        myStack.pop();
        if(node->Rchild)
        {
            myStack.push(node->Rchild);
        }if(node->Lchild)
            myStack.push(node->Lchild);
    }
    printf("\n");
}


void widthSearch(binaryTree * root)
{
    if(NULL == root) return ;
    queue<binaryTree*> myQueue;
    myQueue.push(root);
    binaryTree * node;
    while(!myQueue.empty()){
        node = myQueue.front();
        printf("%c\t", node->val);
        myQueue.pop();
        if(node->Lchild)
            myQueue.push(node->Lchild);
        if (node->Rchild)
            myQueue.push(node->Rchild);
    }
    printf("\n");

}

void CreateBinaryTree(binaryTree* &root, char *list)
{
    char e = list[idx++];
    if(e == '#'){
        root = NULL;
    } else{
        root = (binaryTree*)malloc(sizeof(binaryTree));
        if(root == NULL) {
            printf("malloc() failed\n"); 
        }
        root->val = e;
        CreateBinaryTree(root->Lchild, list);
        CreateBinaryTree(root->Rchild, list);
    }
}

int main() {
    binaryTree* tree;
    CreateBinaryTree(tree, list);
    printf("深度优先遍历二叉树结果: ");
    depthSearch(tree);
    printf("\n\n广度优先遍历二叉树结果: ");
    widthSearch(tree);
    printf("\n");
    return 0;

}

Result

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值