树倒着打印输出

思路

先向右遍历,同时空格也要变多,那么就先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;
}
相关推荐
苏小瀚1 小时前
算法---位运算
java·算法
Code小翊1 小时前
归并排序基础理解
数据结构·算法·排序算法
.小小陈.1 小时前
数据结构2:单链表
c语言·开发语言·数据结构·笔记·学习方法
草莓工作室1 小时前
数据结构4:线性表3-链式存储的线性表
数据结构
雾时之林1 小时前
数据结构--单链表
数据结构
Camel卡蒙1 小时前
数据结构——二叉搜索树Binary Search Tree(介绍、Java实现增删查改、中序遍历等)
java·开发语言·数据结构
2401_841495641 小时前
【数据结构】基于Floyd算法的最短路径求解
java·数据结构·c++·python·算法··floyd
立志成为大牛的小牛1 小时前
数据结构——二十三、并查集的终极优化(王道408)
开发语言·数据结构·笔记·学习·程序人生·考研
珊珊而川2 小时前
SAUP 算法
算法
.YM.Z2 小时前
数据结构——链表(二)
数据结构·链表