树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
GalaxyPokemon5 分钟前
LeetCode - 1089. 复写零
数据结构
失散137 分钟前
分布式专题——1.2 Redis7核心数据结构
java·数据结构·redis·分布式·架构
Moonbit31 分钟前
月报Vol.03: 新增Bitstring pattern支持,构造器模式匹配增强
后端·算法·github
快手技术35 分钟前
多模态大模型Keye-VL-1.5发布!视频理解能力更强!
算法
薛定谔的算法1 小时前
JavaScript数组操作完全指南:从基础到高级
前端·javascript·算法
可爱的小小小狼1 小时前
算法:位运算
算法
zzzsde1 小时前
【数据结构】强化训练:从基础到入门到进阶(1)
数据结构
VisionPowerful1 小时前
九.弗洛伊德(Floyd)算法
算法·c#
可爱的小小小狼1 小时前
算法:哈希表
redis·算法·散列表
奔跑吧 android2 小时前
【linux kernel 常用数据结构和设计模式】【数据结构 3】【模拟input子系统input_dev和input_handler之间的多对多关系】
linux·数据结构·input·kernel·input_dev·input_handler·input_handle