C语言 | 二叉树打印效果,控制台打印

1. 打印效果

复制代码
# 1.demo1
      a
    /    \
   b      c
  /  \    /  \
 d   e   f   /
输入: a b d / / e / / c f / / /
打印效果:
a
├──L:b
│  ├──L:d
│  └──R:e
└──R:c
│  ├──L:f


# 2.demo2
      a
    /    \
   b      c
  /  \    /  \
 d   e   f   /
g h  /\  /i
输入: a b d g / / h / / e / / c f / i / / /
打印效果:相当于拿着左下角掂起来,沾到右上角墙上,其余自然下垂后,恢复原二叉树效果。
a
├──L:b
│  ├──L:d
│  │  ├──L:g
│  │  └──R:h
│  └──R:e
└──R:c
│  ├──L:f
│  │  └──R:i

2. 打印函数

复制代码
//打印二叉树
void printTree(BtNode* root, int depth, char* prefix) {
    if (root == NULL) return;
    
    // 打印当前节点前的基础缩进
    for (int i = 1; i < depth; i++) {
        //printf("%s", (i == depth-1) ? "│  " : "   ");
        printf("%s", "│  ");
    }
    // 打印当前节点的值
    printf("%s%c\n", prefix, root->data);

    // 递归打印子节点
    if (root->lchild || root->rchild) {
        printTree(root->lchild, depth + 1, "├──L:");
        printTree(root->rchild, depth + 1, "└──R:");
    }
}
相关推荐
玖剹3 小时前
Linux文件操作:从C接口到系统调用
linux·服务器·c语言·c++·笔记·ubuntu
屁股割了还要学5 小时前
【数据结构入门】链表
c语言·开发语言·数据结构·c++·学习·算法·链表
焊锡与代码齐飞9 小时前
嵌入式第十八课!!数据结构篇入门及单向链表
c语言·数据结构·学习·算法·链表·排序算法
亿维数组10 小时前
【CSAPP全书详细笔记系列】第一章-计算机系统概述
c语言·笔记·计算机系统
yuyousheng10 小时前
C语言使用GmSSL库实现sm3、sm4算法
c语言·算法·哈希算法
C_Liu_11 小时前
从C语言到C++:拥抱面向对象编程的全新世界
c语言·开发语言·c++
瓦特what?11 小时前
C + +
c语言·开发语言·c++·经验分享·笔记·算法·程序员创富
字节高级特工11 小时前
线程互斥锁:守护临界区的关键
linux·运维·服务器·c语言
刃神太酷啦12 小时前
C++ 容器适配器与核心数据结构精解:栈、队列、deque 底层实现与实战应用----《Hello C++ Wrold!》(17)--(C/C++)
java·c语言·数据结构·c++·qt·算法·leetcode
minichao_sz13 小时前
gdb print设置技巧,离线查看复杂结构体和数组变量内容,展开多层嵌套的结构体的方法
c语言·stm32·嵌入式硬件