用c++实现树的基本功能
时间: 2024-05-06 08:15:50 浏览: 12
树是一种非线性数据结构,由一个根节点和若干个子树组成。每个子树也是一棵树,其根节点是原来树的节点的子节点。以下是C++实现树的基本功能的代码:
```c++
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
vector<TreeNode*> children;
TreeNode(int x) : val(x) {}
};
class Tree {
public:
TreeNode* root;
Tree(int x) {
root = new TreeNode(x);
}
bool addChild(TreeNode* parent, TreeNode* child) {
if (parent == nullptr || child == nullptr) {
return false;
}
parent->children.push_back(child);
return true;
}
void printPreorder(TreeNode* node) {
if (node == nullptr) {
return;
}
cout << node->val << " ";
for (int i = 0; i < node->children.size(); i++) {
printPreorder(node->children[i]);
}
}
void printPostorder(TreeNode* node) {
if (node == nullptr) {
return;
}
for (int i = 0; i < node->children.size(); i++) {
printPostorder(node->children[i]);
}
cout << node->val << " ";
}
};
int main() {
Tree t(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
t.addChild(t.root, n2);
t.addChild(t.root, n3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
t.addChild(n2, n4);
t.addChild(n2, n5);
TreeNode* n6 = new TreeNode(6);
TreeNode* n7 = new TreeNode(7);
t.addChild(n3, n6);
t.addChild(n3, n7);
cout << "Preorder traversal: ";
t.printPreorder(t.root);
cout << endl;
cout << "Postorder traversal: ";
t.printPostorder(t.root);
cout << endl;
return 0;
}
```
上述代码中,我们定义了一个`TreeNode`结构体,每个节点包含一个整数值和一个子节点指针的向量。我们还定义了一个`Tree`类,其中包含一个根节点指针和三个方法:`addChild`、`printPreorder`和`printPostorder`。
`addChild`方法用于向树中添加子节点。如果父节点或子节点为空,则返回false;否则,将子节点添加到父节点的子节点指针向量中,并返回true。
`printPreorder`方法用于先序遍历树。首先输出当前节点的值,然后对当前节点的每个子节点递归调用此方法。
`printPostorder`方法用于后序遍历树。首先对当前节点的每个子节点递归调用此方法,然后输出当前节点的值。
在主函数中,我们创建了一个根节点为1的树,并添加了一些子节点。然后我们使用`printPreorder`方法和`printPostorder`方法分别输出树的先序遍历和后序遍历结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)