树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先prt(root->right,space+cnt) 其中space是离最左边多远,cnt是每次叠加的有多远

输出最右边端点 和 空行

再向左遍历

同样prt(root->left,space+cnt)

代码

cpp 复制代码
#include <iostream>
#include <stack>
using namespace std;

typedef struct Node
{
    struct Node *left;
    struct Node *right;
    char data;
} N, *Tr;

void create(Tr *t)
{
    char ch;
    ch = getchar();
    if (ch == '.')
    {
        *t = NULL;
    }
    else
    {
        *t = (N *)malloc(sizeof(N));
        (*t)->data = ch;
        create(&(*t)->left);
        create(&(*t)->right);
    }
}
void printSpace(int num)
{
    for (int i = 0; i < num; i++)
    {
        cout << " ";
    }
}
void prt(Tr root, int space)
{
    if (root == NULL)
        return;
    int cnt = 1;
    prt(root->right, space + cnt);
    printSpace(space);
    cout << root->data << endl;
    prt(root->left, space + cnt);
}
int main()
{
    Tr Tree;
    create(&Tree);
    prt(Tree, 1);
    return 0;
}
相关推荐
AI科技星5 分钟前
《01无穷全域信息场论:算子G与宇宙本体高维完备公理大典》
人工智能·python·算法·金融·乖乖数学·全域数学
Tim_1019 分钟前
【C++】013、空类占多少字节?
算法
Ricky_Theseus24 分钟前
并查集:连通性问题
算法
Tairitsu_H1 小时前
[LC优选算法#18] 前缀和 | 除⾃⾝以外数组的乘积 | 和为K的⼦数组 | 和可被K整除的⼦数组
算法·前缀和·哈希算法
凯瑟琳.奥古斯特1 小时前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
qq_383189622 小时前
07-运放运用电路-程控增益放大器
算法
aqiu1111112 小时前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表
WL学习笔记2 小时前
链式队列(数据结构)
前端·数据结构·jquery
KaMeidebaby2 小时前
卡梅德生物技术快报|纳米抗体技术全套实操流程:AFB1 全合成文库淘选 + 分子对接定点突变参数手册
人工智能·python·tcp/ip·算法·机器学习
巴糖3 小时前
从做早餐理解 DAG 与拓扑排序:任务依赖图的核心逻辑
算法