简体   繁体   中英

Traversing a n-ary tree

I have the following code for a n-ary tree. I want to traverse the tree but the function is going on in an infinite loop, and will only print the first level of children. It's not going further inside the root->child vector, so as to print out the second level of children. Can someone please comment what I'm doing wrong

#include <iostream>
#include <vector>

using namespace std;



class Node
{


public:

char key;
vector<Node *> child;



};

// Utility function to create a new tree node  
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}

void printTree(Node* root);

int main()
{
/*   Let us create below tree
*           A
*         / /  \  \
*       B  F   D  E
*      / \     |  /|\
*     K  J    G  C H I
*      /\            \
*    N   M            L
*/

Node *root = newNode('A');
(root->child).push_back(newNode('B'));
(root->child).push_back(newNode('F'));
(root->child).push_back(newNode('D'));
(root->child).push_back(newNode('E'));
(root->child[0]->child).push_back(newNode('K'));
(root->child[0]->child).push_back(newNode('J'));
(root->child[2]->child).push_back(newNode('G'));
(root->child[3]->child).push_back(newNode('C'));
(root->child[3]->child).push_back(newNode('H'));
(root->child[3]->child).push_back(newNode('I'));
(root->child[0]->child[0]->child).push_back(newNode('N'));
(root->child[0]->child[0]->child).push_back(newNode('M'));
(root->child[3]->child[2]->child).push_back(newNode('L'));

printTree(root);

system ("PAUSE");
return 0;

}


void printTree(Node* root)
{
    if (!root->child.empty())
        for(int i=0; i < root->child.size(); i++)
            cout<<root->child[i]->key<<endl;

    printTree(root->child);
}

I'm surprised that even even compiles for you - I'm getting

error: cannot convert ‘std::vector<Node*>’ to ‘Node*’ for argument ‘1’ to ‘void printTree(Node*)’

which happens because you pass a Vector to the recursive printTree call, while it is expecting a pointer to a node. I suspect what's happening is that is auto-converts the vector to a pointer, resulting in some "random" pointer, causing the code to misbehave.

Try to replace printTree(root->child) with printTree(&root->child[0]) if you want to print only the first child, or otherwise move the recursive call into the loop, calling printTree(&root->child[i]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM