其他典型算法-第1关:DFS于BFS

该程序定义了一个二叉树节点结构,通过输入的指令创建二叉树,并使用广度优先搜索(BFS)进行遍历。输入格式为一对括号包含一个整数和方向指示符,用于指定节点的值和位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>

#include<string.h>

using namespace std;

/********** Begin **********/

// 定义全局变量,结构体,函数等

struct TNode {

    int data;

    TNode* left;

    TNode* right;

};

TNode* newnode()

{

    TNode * node = (TNode*)malloc(sizeof(TNode));

    node->data = -1;

    node->left = NULL;

    node->right = NULL;

    return node;

}

char s[500];

void addnode(TNode* root, int value, char* instruct) {

    int index = 0;

    TNode* node = root;

    while (instruct[index] != ')') {

       

        if (instruct[index] == 'L') {

            if(node->left == NULL)

                node->left = newnode();

            node = node->left;

        }

        if (instruct[index] == 'R') {

            if (node->right == NULL)

                node->right = newnode();

            node = node->right;

        }

        index++;

    }

    node->data = value;

}

bool input(TNode* root){

    bool failed=false;

    while(true){

        if(scanf("%s",s)!=1) return false;

        if(!strcmp(s,"()")) break;   // 两个字符穿相同对于零

        int v;

        sscanf(&s[1],"%d",&v);

        addnode(root,v,strchr(s,',')+1);

    }

    return true;

}

void BFS(TNode* root) {

    TNode* queue[100];

    TNode* p;

    int front = 0, rear = 0;

    queue[front++] = root;

    while (front != rear) {

        p = queue[rear++];

        printf("%d", p->data);

        if (p->data == -1)

            return;

        if (p->left != NULL) {

            queue[front++] = p->left;

        }

        if (p->right != NULL) {

            queue[front++] = p->right;

        }

        if (front != rear) {

            printf(" ");

        }

    }

    printf("\n-1\n");

}

/********** End **********/

int main(){

    TNode * root = newnode();

    bool a = input(root);

    BFS(root);

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值