写一个c++树结构,每个节点有唯一id,支持添加节点,删除节点,获取节点
时间: 2023-12-07 14:02:28 浏览: 40
以下是一个简单的C++树结构,每个节点包含一个唯一的id和节点的子节点列表。它支持添加节点,删除节点和获取节点。
```cpp
class TreeNode {
public:
int id;
vector<TreeNode*> children;
TreeNode(int _id) {
id = _id;
}
~TreeNode() {
for (auto child : children) {
delete child;
}
}
TreeNode* addChild(int childId) {
auto child = new TreeNode(childId);
children.push_back(child);
return child;
}
void removeChild(TreeNode* child) {
auto it = find(children.begin(), children.end(), child);
if (it != children.end()) {
children.erase(it);
delete child;
}
}
TreeNode* getNodeById(int nodeId) {
if (id == nodeId) {
return this;
}
for (auto child : children) {
auto node = child->getNodeById(nodeId);
if (node) {
return node;
}
}
return nullptr;
}
};
```
使用示例:
```cpp
auto root = new TreeNode(0);
auto node1 = root->addChild(1);
auto node2 = root->addChild(2);
auto node3 = node1->addChild(3);
auto node = root->getNodeById(3);
if (node) {
cout << "Found node with id 3" << endl;
} else {
cout << "Node with id 3 not found" << endl;
}
node1->removeChild(node3);
delete root;
```
这个例子创建了一个树形结构,包含4个节点。使用getNodeById函数可以获取具有特定id的节点。使用removeChild函数可以删除节点。最后,删除根节点会自动删除所有子节点。
相关推荐
![](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)