[英]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.