树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
Funny_AI_LAB1 小时前
李飞飞联合杨立昆发表最新论文:超感知AI模型从视频中“看懂”并“预见”三维世界
人工智能·算法·语言模型·音视频
RTC老炮4 小时前
webrtc降噪-PriorSignalModelEstimator类源码分析与算法原理
算法·webrtc
草莓火锅6 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
散峰而望6 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
摇滚侠6 小时前
StreamAPI,取出list中的name属性,返回一个新list
数据结构·list
Kuo-Teng6 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie88897 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
偷偷的卷7 小时前
【算法笔记 11】贪心策略六
笔记·算法
ZPC82108 小时前
FPGA 部署ONNX
人工智能·python·算法·机器人
_w_z_j_8 小时前
爱丽丝的人偶
算法