洛谷题单指南-二叉树-P1305 新二叉树

原题链接:https://www.luogu.com.cn/problem/P1305

题意解读:二叉树的建立和前序遍历,主要注意每个节点值是小写字母。

解题思路:

树的存储:

struct node
{
    char value;
    int l, r;
} tree[30];

对于节点a,存到第1个,即tree['a' - 'a' + 1]的位置,规定如果节点号是0则表示空节点。

其余就是常规的建树、前序遍历的过程,参考代码。

100分代码:

#include <bits/stdc++.h>
using namespace std;

struct node
{
    char value;
    int l, r;
} tree[30];

int n;
char c, l, r;

void dfs(int root)
{
    if(root == 0) return;
    cout << tree[root].value;
    if(tree[root].l) dfs(tree[root].l);
    if(tree[root].r) dfs(tree[root].r);
}

int main()
{
    int root;
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        cin >> c >> l >> r;
        if(i == 1) root = c - 'a' + 1;

        tree[c - 'a' + 1].value = c;
        if(l != '*') tree[c - 'a' + 1].l = l - 'a' + 1;
        if(r != '*') tree[c - 'a' + 1].r = r - 'a' + 1;
    }
    dfs(root);

    return 0;
}

 

posted @   五月江城  阅读(75)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示