树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
Frostnova丶8 小时前
【算法笔记】数学知识
笔记·算法
吴可可1239 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白10 小时前
哈希:以时间换空间的算法实战
算法
啦啦啦啦啦zzzz11 小时前
数据结构:红黑树理论
数据结构·c++·红黑树
San813_LDD12 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x1387028595712 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199813 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油13 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero14 小时前
Guava Cache Deep Dive
java·后端·算法·guava