【数据结构】二叉树DFS(深度优先搜索)

文章详细介绍了如何在C++中使用静态数组实现二叉树结构,包括节点定义、插入操作以及深度优先遍历(dfn_order)、广度优先遍历(visit_order)、深度计算(deep_node)、节点计数(num_node)等。同时展示了链表的简单实现,包括预序、中序和后序遍历,以及删除整个树的操作。

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

静态实现(数组)

#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
struct Node{
    char value;
    int lson, rson;
}tree[N];
int index=1;
int newNode(char val)
{
    tree[index].value=val;
    tree[index].lson=tree[index].rson=0;
    return index++;
}
void insert(int &father,int child,int l_r){
    if(l_r==0)
        tree[father].lson=child;
    else
        tree[father].rson=child;

}

int dfn[N]={0};
int dfn_timer=0;

void dfn_order(int father)
{
    if(father!=0){
        dfn[father]=++dfn_timer;
        printf("dfn[%c]=%d;",tree[father].value,dfn[father]);
        dfn_order(tree[father].lson);
        dfn_order(tree[father].rson);
    }
}

int visit_timer=0;
void visit_order(int father)
{
    if(father!=0){
        printf("visit[%c]=%d;",tree[father].value,++visit_timer);
        visit_order(tree[
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值