树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
醉城夜风~3 分钟前
[数据结构]堆详解
开发语言·数据结构
苏言の狗9 分钟前
小R的并集大小期望计算 | 蛮力
数据结构·算法
BineHello15 分钟前
MPC用优化求解器 - 解决无人机轨迹跟踪
算法·矩阵·自动驾驶·动态规划·无人机
橘颂TA16 分钟前
每日一练之链表的回文结构
数据结构·链表
誓约酱17 分钟前
(每日一题) 力扣 14 最长公共前缀
算法·leetcode·职场和发展
刃神太酷啦20 分钟前
数据结构(蓝桥杯常考点)
数据结构·c++·蓝桥杯c++组
冠位观测者1 小时前
【Leetcode 每日一题 - 补卡】2070. 每一个查询的最大美丽值
数据结构·算法·leetcode
誓约酱1 小时前
(每日一题) 力扣 860 柠檬水找零
linux·c语言·c++·算法·leetcode·职场和发展
地平线开发者1 小时前
手把手基于 MINI 数据集带你做一次板端精度评估
算法·自动驾驶
詹天佐1 小时前
ICCE 数字车钥匙介绍
人工智能·算法