树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯
Allen Wurlitzer3 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
百锦再5 小时前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
碳基学AI6 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
独家回忆3647 小时前
每日算法-250410
算法
袖清暮雨7 小时前
Python刷题笔记
笔记·python·算法
Marzlam7 小时前
一文读懂数据结构
数据结构
南玖yy7 小时前
探索 C 语言数据结构:从基础到实践
c语言·开发语言·数据结构
风掣长空7 小时前
八大排序——c++版
数据结构·算法·排序算法
流星白龙8 小时前
【C++算法】50.分治_归并_翻转对
c++·算法