c++写一个树结构,支持节点添加,节点删除,获取节点,获取子节点
时间: 2023-12-02 07:06:41 浏览: 36
好的,下面是一个简单的C++树结构示例,包含节点添加,节点删除,获取节点和获取子节点功能:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 树的节点类
class TreeNode {
public:
int val; // 节点值
vector<TreeNode*> children; // 子节点指针数组
// 构造函数
TreeNode(int val) {
this->val = val;
}
// 添加子节点
void addChild(TreeNode* node) {
children.push_back(node);
}
// 删除子节点
void removeChild(TreeNode* node) {
for (int i = 0; i < children.size(); i++) {
if (children[i] == node) {
children.erase(children.begin() + i);
return;
}
}
}
// 获取子节点
vector<TreeNode*> getChildren() {
return children;
}
};
int main() {
// 创建根节点
TreeNode* root = new TreeNode(1);
// 添加子节点
TreeNode* node1 = new TreeNode(2);
TreeNode* node2 = new TreeNode(3);
root->addChild(node1);
root->addChild(node2);
// 获取子节点
vector<TreeNode*> children = root->getChildren();
for (int i = 0; i < children.size(); i++) {
cout << children[i]->val << " ";
}
cout << endl;
// 删除子节点
root->removeChild(node1);
children = root->getChildren();
for (int i = 0; i < children.size(); i++) {
cout << children[i]->val << " ";
}
cout << endl;
return 0;
}
```
该示例实现了一个简单的树结构,包括节点添加,节点删除,获取节点和获取子节点功能。你可以根据需要对其进行改进和扩展。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)