树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
小白菜又菜4 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n5 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo6 小时前
leetcode 2483
数据结构·算法·leetcode
Xの哲學6 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢6 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
油泼辣子多加7 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
一路往蓝-Anbo7 小时前
【第20期】延时的艺术:HAL_Delay vs vTaskDelay
c语言·数据结构·stm32·单片机·嵌入式硬件
Aaron15887 小时前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程
laocooon5238578867 小时前
插入法排序 python
开发语言·python·算法
wuhen_n8 小时前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展