思路
先向右遍历,同时空格也要变多,那么就先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;
}