TXT

TreeToBTree

By Brittany Gonzales,2014-01-19 20:10
9 views 0
TreeToBTree

// TreeToBTree.cpp : ??Òå?ØÖÆÌ?Ó?ÓÃ?ÌÐòµÄÈë?Úµã

    //

#include "stdafx.h"

    #include <string>

    #include<iostream>

    #include <iomanip>

    using namespace std ;

struct Node

    { //ÒÔ?íµÄÐÎÊ??æ??µÄÊ??áµã

     char data;

     int parent;

     int lchild;

     int rchild;

    };

    struct TreeNode { //ÒÔ?þ?æÁ??í?æ??µÄÊ?µÄ?áµã

     char data;

     TreeNode* l;

     TreeNode* r;

    };

TreeNode * b;

    void graph(ostream & out);

    void graphaux(ostream & out,int indent,TreeNode * subtreeRoot);

    int creattable( Node table[]) { //????Ê?µÄ?í??ת??Ϊ?þ?æÊ?

     int n,k,i,j;

     cout<<"????Ê???\n";

     cout<<"ÊäÈë?áµã?öÊý:";

     cin>>n;

     if ( n>0 )

     {

     cout<<"ÊäÈë?áµãÐÅÏ???×Ö?û??ºÍË?Ç×?àºÅ(?ù?ÚµãΪ-1???ß?È?Ó1Öµ?Ó1

    ):"<<endl;

     for( i = 0; i < n; i++){

     cin>>table[i].data>>table[i].parent;

     table[i].lchild = table[i].rchild = 0;

     }

     for( i = 0; i < n; i++ )

     {

     for( j = 1;j < n; j++ )

     {

     if( table[j].parent == i )

     if( table[i].lchild == 0 )

     {

     table[i].lchild = j;

     k = j;

     }

     else

     {

     table[k].rchild = j;

     k = j;

     }

     }

     }

     for( i = 0; i < n; i++)

     cout<<i<<" "<<table[i].data<<" "<<table[i].parent<<"

    "<<"×ó×ÖÊ?:"<<table[i].lchild<<" "<<"ÓÒ×ÖÊ?:"<<table[i].rchild<<endl;

     }

     return n;

    }

    void Build ( TreeNode*& current,Node node[], int pos ,int n )

    { //???íת??Ϊ?þ?æÁ??í

     if (n>0)

     {

     if ( current == 0 )

     {

     current = new TreeNode;

     current->l = current->r = 0;

     }

     current->data = node[pos].data;

     if (node[pos].lchild )

     Build( current->l, node, node[pos].lchild, n);

     if (node[pos].rchild )

     Build( current->r ,node, node[pos].rchild, n);

     }

    }

    int _tmain(int argc, _TCHAR* argv[]) {

     Node node [20];

     int n = creattable( node );

     TreeNode* root = 0;

     Build ( root, node, 0 , n);

     b=root;

     graph(cout);

     return 0;

    }

void graph(ostream & out)

     {

     graphaux(out,0,b);

     }

     void graphaux(ostream& out,int indent,TreeNode* subtreeRoot)

     {

     if(subtreeRoot!=0)

     {

     graphaux(out,indent+8,subtreeRoot->r);

     out<<setw(indent)<< " "<<subtreeRoot->data<<endl;

     graphaux(out,indent+8,subtreeRoot->l);

     }

     }

Report this document

For any questions or suggestions please email
cust-service@docsford.com