树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
Yvonne爱编码14 小时前
JAVA数据结构 DAY1-集合和时空复杂度
java·数据结构·python
iAkuya14 小时前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先
m0_7369191014 小时前
模板元编程性能分析
开发语言·c++·算法
pen-ai14 小时前
【YOLO系列】 YOLOv1 目标检测算法原理详解
算法·yolo·目标检测
2301_7657031414 小时前
C++中的职责链模式实战
开发语言·c++·算法
StandbyTime15 小时前
《算法笔记》学习记录-第一章
c++·算法·算法笔记
近津薪荼15 小时前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
松☆15 小时前
Dart 中的常用数据类型详解(含 String、数字类型、List、Map 与 dynamic) ------(2)
数据结构·list
格林威15 小时前
Baumer相机铆钉安装状态检测:判断铆接是否到位的 5 个核心算法,附 OpenCV+Halcon 的实战代码!
人工智能·opencv·算法·计算机视觉·视觉检测·工业相机·堡盟相机
星空露珠15 小时前
速算24点检测生成核心lua
开发语言·数据库·算法·游戏·lua