所以这里是一个二叉树,如果创建,[不再是BT]将这个变成一般树/动态创建子树然后可以执行DFS / BFS需要哪些步骤?
编辑:
为儿童添加了Node Vector,我是否在正确的轨道上?请记住,我将不得不动态生成char数组(或int数组)的子代,(不像我在这里硬编码的那样)。
如果我正确地进行实施,你能否以正确的方式指导我动态生成孩子,以便字符串" 012345678"将有2个孩子(" 102345678")& (" 312045678"),或字符串" 283164705"将有3个孩子(" 283164075")& (" 283104765")& (" 283164754&#34)。
#include <iostream>
#include <vector>
using namespace std;
struct Node{
char data;
Node *next;
};
void AddNode(Node *&listpointer, char newdata){
Node *current;
current = listpointer;
if(current != NULL){
while(current -> next != NULL){
current = current->next;
}
}
Node *temp;
temp = new Node;
temp->data = newdata;
temp->next = NULL;
if(current != NULL){
current->next = temp;
}
else{
listpointer = temp;
}
}
void PrintLL(Node *&listpointer)
{
Node *temp;
temp = listpointer;
if(temp == NULL){return;}
int element = 1;
while(true){
if(temp == NULL) break;
cout << "Element " << element << " is: " << temp->data <<endl;
temp = temp->next;
element++;
}
cout <<"End of list"<<endl;
}
class Tree{
private:
vector<Node *> children;
public:
Tree(){}
~Tree(){}
void AddChild(Node *child);
void PrintChildren();
vector<Node *> GetChildren(){return children;}
};
void Tree::AddChild(Node *child){
children.push_back(child);
}
void Tree::PrintChildren(){
int i = 1;
for(int j = 0; j < children.size(); j++){
cout << "Child # " << i << ": " <<children[j]->data<<endl;
i++;
}
}
Tree *T1, *T2;
Node *A, *B, *C, *D;
int main(){
AddNode(A, 'a');
AddNode(B, 'b');
AddNode(C, 'c');
AddNode(D, 'd');
T1 = new Tree();
T1->AddChild(A);
T1->AddChild(B);
T1->AddChild(C);
T1->AddChild(D);
T1->PrintChildren();
}