//
// Created by 徐昌真 on 2024/11/10.
//
#include <iostream>
using namespace std;
template<typename T>
struct ListNode{ //新建链表节点
T data; //指向下一个子节点 ListNode< TreeNode<T>* > childHead; 这里的 T 是TreeNde类型的指针
ListNode *next; //指向兄弟节点
ListNode(T d): data(d), next(NULL) {}
};
template<typename T>
struct TreeNode{ //树节点
T data;
ListNode< TreeNode<T>* > *childHead;
TreeNode(): childHead(NULL) {}
void addChild(TreeNode<T>* node){ //插入孩子节点
ListNode < TreeNode<T>* > *childNode = new ListNode< TreeNode<T>* > (node); //childNode保存了对node的指针 也就是node的地址
if (childHead == NULL){
childHead = childNode;
}else{
childNode->next = childHead;
childHead = childNode;
}
}
};
template<typename T>
class Tree{
private:
TreeNode<T> *nodes;
TreeNode<T> *root;
public:
Tree();
Tree(int MaxNodes);
~Tree();
TreeNode<T>* GetTreeNode(int id);
void SetRoot(int rootId);
void AddChild(int parentId, int sonId);
void AssignData(int nodeId, T data);
void Print(TreeNode<T> *node = NULL);
};
template<typename T>
Tree<T>::Tree(){ //默认构造函数
nodes = new TreeNode<T>[100001];
}
template<typename T>
Tree<T>::Tree(int maxNodes) { //传参构造函数
nodes = new TreeNode<T>[maxNodes];
}
template<typename T>
Tree<T>::~Tree(){ //析构
delete[] nodes;
}
template<typename T>
TreeNode<T>* Tree<T>::GetTreeNode(int id) { //获取节点指针
return &nodes[id];
}
template<typename T>
void Tree<T>::SetRoot(int rootId) { //设置根节点
root = GetTreeNode(rootId);
}
template<typename T>
void Tree<T>::AddChild(int parentId, int sonId) { //连接父子
TreeNode<T>* parentNode = GetTreeNode(parentId);
TreeNode<T>* sonNOde = GetTreeNode(sonId);
parentNode->addChild( sonNOde );
}
template<typename T>
void Tree<T>::AssignData(int nodeId, T data) { //给节点赋值
GetTreeNode(nodeId)->data = data;
}
template<typename T>
void Tree<T>::Print(TreeNode<T> *node) {
if (node == NULL){
node = root;
}
cout << node->data << ' ';
ListNode< TreeNode<T>* > *tmp = node->childHead;
while(tmp){
Print(tmp->data);
tmp = tmp->next;
}
}
int main() {
Tree<char> T(6);
T.SetRoot(0);
T.AssignData(0, 'a'); //节点添加值
T.AssignData(1, 'b');
T.AssignData(2, 'c');
T.AssignData(3, 'd');
T.AssignData(4, 'e');
T.AssignData(5, 'f');
T.AddChild(0, 2);
T.AddChild(0, 1);
T.AddChild(1, 3);
T.AddChild(1, 4);
T.Print();
return 0;
}
输出
疑难杂症
https://chatgpt.com/share/6731dae1-5b54-800c-8ecd-4eebe00a91a7
https://chatgpt.com/share/67315d8d-46c0-800c-968b-822ae6337414