繁体   English   中英

遍历一元树

[英]Traversing a n-ary tree

我有以下代码用于n元树。 我想遍历该树,但是该函数在无限循环中进行,并且只会打印第一级子级。 在root-> child向量中,它不会走得更远,以便打印出第二级子级。 有人可以评论我在做什么错

#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);
}

我很惊讶甚至为您编译-我越来越

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

之所以发生这种情况,是因为您将Vector传递给递归的printTree调用,而它却期望指向节点的指针。 我怀疑正在发生的事情是将向量自动转换为指针,导致出现了一些“随机”指针,从而导致代码行为异常。

如果您只想打印第一个孩子,请尝试用printTree(&root->child[0])替换printTree(root->child) ,否则将递归调用移入循环,调用printTree(&root->child[i])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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