树形数据结构,输出的时候采用prestr保存数字之前的.和|
#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
#include <cstring>
using namespace std;
struct BTNode{
int data, len, dis;
BTNode *lchild, *rchild;
}*root;
char prestr[1000],back[1000];
void Create(BTNode *bt, int value, BTNode *father){
if (bt == NULL){
bt = new BTNode;
bt->data = value;
bt->dis = father->dis + father->len;
bt->len = log10(value) + 4.00001;
bt->lchild = bt->rchild = NULL;
if (value > father->data)
father->rchild = bt;
else
father->lchild = bt;
}
else if (bt->data < value)
Create(bt->rchild, value, bt);
else
Create(bt->lchild, value, bt);
}
void PostOrder(BTNode* bt,bool left,bool right,int pos){
if (bt != NULL){
if (bt->rchild){
if (right){
//strncpy(back, prestr, 1000);
//memset(prestr, '.', bt->dis + bt->len);
prestr[pos] = '.';
prestr[bt->dis + bt->len + 1] = '|';
PostOrder(bt->rchild, false, true, bt->dis + bt->len + 1);
prestr[pos] = '|';
prestr[bt->dis + bt->len + 1] = '.';
//strncpy(prestr, back, 1000);
}
else
{
prestr[bt->dis + bt->len + 1] = '|';
PostOrder(bt->rchild, false, true, bt->dis + bt->len + 1);
prestr[bt->dis + bt->len + 1] = '.';
}
}
if (bt != root){
int n = bt->dis;
for(int i=1;i<=n;i++){
cout << prestr[i];
}
cout << "|-";
}
cout << bt->data;
if (bt->lchild||bt->rchild)
cout<<"-|" ;
cout << endl;
if (bt->lchild){
if (left){
//strncpy(back, prestr, 1000);
//memset(prestr, '.', bt->dis + bt->len);
prestr[pos] = '.';
prestr[bt->dis + bt->len + 1] = '|';
PostOrder(bt->lchild, true, false, bt->dis + bt->len + 1);
prestr[bt->dis + bt->len + 1] = '.';
prestr[pos] = '|';
//strncpy(prestr, back, 1000);
}
else
{
prestr[bt->dis + bt->len + 1] = '|';
PostOrder(bt->lchild, true, false, bt->dis + bt->len + 1);
prestr[bt->dis + bt->len + 1] = '.';
}
}
}
}
int main()
{
//ifstream cin("D:\\input.txt");
memset(prestr, '.', 1000);
root = new BTNode;
cin >> root->data;
root->len = log10(root->data) + 2.00001;
root->dis = 0;
root->lchild = root->rchild = NULL;
int value;
while (cin >> value){
Create(root, value, root);
}
PostOrder(root,false,false,0);
//system("PAUSE");
return 0;
}