读书人

求教怎么创建一个N叉树且树的高度

发布时间: 2012-11-09 10:18:48 作者: rapoo

求教,如何创建一个N叉树,且树的高度为7
是用递归创建N叉树,但是不知道要怎么控制树的高度为7,求指点

[解决办法]
创建d层N叉树。

C/C++ code
#include <iostream>#include <queue>using namespace std;#define N 3                //N叉树struct Node{    int data;    Node *child[N];};//创建一颗N叉数,树的高度为depthNode *CreateTree( int depth ){    if( depth <1 ) return NULL;    Node * node = new Node();    node->data = depth;    if( depth==1){        for( int i=0; i<N; i++)            node->child[i] = NULL;    }    else{        for( int i=0; i<N; i++)            node->child[i] = CreateTree( depth-1 );    }    return node;}//返回一颗树的高度int FindDepth( Node * tree ){    if( ! tree ) return 0;    else{        int max = FindDepth( tree->child[0] );        for( int i=1; i<N; i++){            int d=FindDepth(tree->child[i]);            if( d>max ) max = d;        }        return max+1;    }}void Print( char ch, int num ){    if( num <=0 ) return;    while( num-- )        cout <<ch;}//打印树的内容,显示到屏幕void PrintTree( Node * tree){    if( !tree ){        cout <<"The tree is empty" <<endl;        return;    }    int depth = FindDepth( tree );    deque<Node*> queue;    queue.push_back( tree );    queue.push_back( NULL );        //增加一个标志    while( (int)queue.size()>1 ){        depth--;        for( int i=0; i<queue.size()-1; i++ ){            if( i==0 )                Print(' ',depth*depth);            cout << queue[i]->data;            Print(' ',2*depth+1);        }                cout << endl;                while(1){            Node * node = queue.front();            queue.pop_front();            if( node != NULL ){                for( int i=0; i<N; i++)                    if( node->child[i] )                        queue.push_back( node->child[i] );            }            else{                queue.push_back( NULL );                break;            }        }    }}int main(){    int depth = 7;    Node * tree =CreateTree( depth );    PrintTree( tree);    return 0;} 

读书人网 >软件架构设计

热点推荐