C++已知一颗树的节点间关系,请编程实现该树的先根遍历
时间: 2024-03-17 18:41:16 浏览: 34
以下是C++实现先根遍历的代码,假设节点的定义如下:
```c++
struct TreeNode {
int val;
vector<TreeNode*> children;
TreeNode(int x) : val(x) {}
};
```
先根遍历的实现代码如下:
```c++
void preorderTraversal(TreeNode* root) {
if (root == nullptr) {
return;
}
cout << root->val << " "; // 访问当前节点
// 递归访问子节点
for (auto child : root->children) {
preorderTraversal(child);
}
}
```
在主函数中,我们可以按照以下方式构建一个树并进行先根遍历:
```c++
int main() {
// 构建一颗树
TreeNode* root = new TreeNode(1);
TreeNode* node2 = new TreeNode(2);
TreeNode* node3 = new TreeNode(3);
root->children.push_back(node2);
root->children.push_back(node3);
TreeNode* node4 = new TreeNode(4);
TreeNode* node5 = new TreeNode(5);
node2->children.push_back(node4);
node2->children.push_back(node5);
TreeNode* node6 = new TreeNode(6);
node3->children.push_back(node6);
// 先根遍历
preorderTraversal(root);
return 0;
}
```
输出结果为:1 2 4 5 3 6
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)