2018.5.22(树的图形化显示-理解)

//需在加头文件#include<windows.h>
//GraphShow()函数中x,y为输出结点的坐标,k=0,1,2分别代表结点为根,左子,右子,space控制输出的树宽度
//改程序仅能在windows平台上运行
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<windows.h>
using namespace std;

struct Tree
{
    int data;
    Tree *left,*right;
};

Tree *Insert(Tree *head,int node)
{
    Tree *current_point,*parent_point;
    Tree *new_point;

    new_point=(Tree *)malloc(sizeof(Tree));
    new_point->data=node;
    new_point->left=NULL;
    new_point->right=NULL;

    if(head==NULL)
        return new_point;

    current_point=head;
    while(current_point!=NULL)
    {
        parent_point=current_point;

        current_point=(node>current_point->data)?current_point->right:current_point->left;
    }
    if(node>parent_point->data)
        parent_point->right=new_point;
    else
        parent_point->left=new_point;

    return head;
}

Tree *Create(int node[],int len)
{
    Tree *head=NULL;

    for(int i=1;i<=len;i++)
        head=Insert(head,node[i]);

    return head;
}

void GraphShow(Tree *head,int x,int y,int k,int space)
{
    if(head!=NULL)
    {
        //此段代码用于定位光标,可令写成函数调用的形式
        HANDLE hOutput;
        COORD location;
        location.X=x;
        location.Y=y;
        hOutput=GetStdHandle(STD_OUTPUT_HANDLE);//获得屏幕句柄
        SetConsoleCursorPosition(hOutput,location);//定位光标到坐标(x,y)处

        if(k==1)
            cout<<head->data<<"/";//输出表示左子树
        else if(k==2)
            cout<<"\\"<<head->data;//输出表示右子树
        else
            cout<<head->data;//输出根节点
        GraphShow(head->left,x-space,y+1,1,space/2);
        GraphShow(head->right,x+space,y+1,2,space/2);
    }
}

int main()
{
    Tree *head;
    int n;

    while(cin>>n)
    {
        if(n==0)
            break;
        int node[n+1];
        for(int i=1;i<=n;i++)
            cin>>node[i];

        head=Create(node,n);
        GraphShow(head,40,3,0,20);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/violet_ljp/article/details/80411001
今日推荐