树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
soragui11 分钟前
【Python】第 4 章:Python 数据结构实现
数据结构·windows·python
sinat_2869451936 分钟前
harness engineering
人工智能·算法·chatgpt
少许极端1 小时前
算法奇妙屋(四十三)-贪心算法学习之路10
学习·算法·贪心算法
samroom1 小时前
【鸿蒙应用开发 Dev ECO Studio 5.0版本】从0到1!从无到有!最全!计算器------按钮动画、滑动退格、中缀表达式转后缀表达式、UI设计
数据结构·ui·华为·typescript·harmonyos·鸿蒙
算法鑫探1 小时前
10个数下标排序:最大值、最小值与平均值(下)
c语言·数据结构·算法·排序算法·新人首发
样例过了就是过了1 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
IronMurphy1 小时前
【算法三十七】51. N 皇后
算法·深度优先
DoUfp0bgq1 小时前
从直觉到算法:贝叶斯思维的技术底层与工程实现
算法
ThisIsMirror1 小时前
leetcode 452 Arrays.sort()排序整数溢出、Integer.compare(a[1], b[1])成功的问题
算法·leetcode
王老师青少年编程1 小时前
csp信奥赛c++之状压枚举
数据结构·c++·算法·csp·信奥赛·csp-s·状压枚举