树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
一只齐刘海的猫15 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏11116 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
liulilittle16 小时前
固定数组时间轮的槽过载优化:桶链表与批次执行
网络·数据结构·链表
IronMurphy17 小时前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe17 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白17 小时前
数据容器集合set/frozenset
数据结构
凌波粒17 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle17 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂18 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件