首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

多叉树的如何非递归建立

2012-10-20 
多叉树的怎么非递归建立?Node *createMultTree(const char *str, int n)//将str字符串建立成n叉树完善这

多叉树的怎么非递归建立?
Node *createMultTree(const char *str, int n); //将str字符串建立成n叉树


完善这个函数,并显示该N叉树。

我的思路:
typde struct node
{
  char data;
  vector<struct node*> child; //因为n叉树,n是参数变化的,所以用到vector
}Node;

接下来我准备递归建立该树的,但。。。说“怎么需要递归呢? 不需要递归。”

于是我想来想去,敲来敲去,硬是不知道怎么非递归建立多叉树;
讨论说我觉得应该需要递归建立,他还是说不需要。
我真心不知道怎么弄。求解!

需哪位大牛能指点一二! 非递归的二叉树还是可以的,但是如果N大的话,试问怎么非递归来弄。。



[解决办法]

C/C++ code
typedef struct node    {        char data;        int depth;        vector<struct node*> child; //因为n叉树,n是参数变化的,所以用到vector    }Node;    Node *createMultTree(const char *str, int n)    {        stack<Node*> ns;        Node* parent = NULL,*ret = NULL;        for(int i = 0 ; str[i] ; ++ i)        {            if(str[i] == '(')            {                if(!ns.empty())                    parent = ns.top();            }            else if(str[i] == ')')            {                if(!ns.empty())                    ns.pop();                if(!ns.empty())                                    parent = ns.top();            }            else            {                Node* p = new Node;                p->data = str[i];                if(!parent)                 {                    p->depth = 0;                    ret = parent = p;                }                else                {                    p->depth = parent->depth + 1;                    parent->child.push_back(p);                }                if(str[i + 1] == '(')                    ns.push(p);            }        }        return ret;    }    void print(Node* parent,Node* root)    {        if(parent)        {            int n = parent->depth * 2;            while(n--)cout<<' ';            cout<<"|-";        }        cout<<root->data<<endl;        for_each(root->child.begin(),root->child.end(),bind1st(ptr_fun(print),root));    } 

热点排行