树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
2401_851272992 分钟前
多平台UI框架C++开发
开发语言·c++·算法
楼田莉子9 分钟前
C++数据结构:基数树
开发语言·数据结构·c++·学习
m0_5180194810 分钟前
C++中的命令模式实战
开发语言·c++·算法
Tisfy13 分钟前
LeetCode 2906.构造乘积矩阵:前后缀分解
算法·leetcode·前缀和·矩阵·题解·前后缀分解
weixin_6495556732 分钟前
C语言程序结构第四版(何钦铭、颜晖)第十章函数与程序结构之递归实现顺序输出整数
c语言·数据结构·算法
想七想八不如1140834 分钟前
复试简历复盘--CV论文
算法
cm65432036 分钟前
C++中的空对象模式
开发语言·c++·算法
2401_8512729937 分钟前
C++代码规范化工具
开发语言·c++·算法
Yzzz-F43 分钟前
Problem - 2167F - Codeforces
算法
MORE_7743 分钟前
leecode100-跳跃游戏-贪心算法
算法·游戏·贪心算法