树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
lisw052 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
阿卡好可爱2 小时前
Lua 热更新不生效:改完文件线上仍是旧逻辑,package.loaded 与 upvalue 重绑定详解
数据结构·分布式·后端·架构·lua
一起学安全技术3 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs4 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信150413057594 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI15 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi16 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M18 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen19 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#