树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
-Rane10 小时前
【C++】vector
开发语言·c++·算法
代码栈上的思考10 小时前
滑动窗口算法实战
算法
Eloudy10 小时前
直接法 读书笔记 06 第6章 LU分解
人工智能·算法·ai·hpc
仰泳的熊猫10 小时前
题目1531:蓝桥杯算法提高VIP-数的划分
数据结构·c++·算法·蓝桥杯
刘琦沛在进步11 小时前
如何计算时间复杂度与空间复杂度
数据结构·c++·算法
m0_6727033111 小时前
上机练习第30天
数据结构·算法
9359611 小时前
机考31 翻译25 单词18
c语言·算法
每天要多喝水11 小时前
单调栈Day36:接雨水
算法
AI科技星12 小时前
时空的几何本源与物理现象的建构:论统一场论的宇宙二元论与观察者中心范式
人工智能·线性代数·算法·矩阵·数据挖掘
CelestialYuxin12 小时前
A.R.I.S.系统:YOLOx在破碎电子废料分拣中的新探索
人工智能·深度学习·算法