代码生成,用C++编写遍历二叉树
时间: 2023-06-08 07:06:17 浏览: 113
建立遍历二叉树C++
好的,您希望我为您生成遍历二叉树的 C 代码。以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void traverse(struct TreeNode* root) {
if (root != NULL) {
traverse(root->left);
printf("%d ", root->val);
traverse(root->right);
}
}
int main() {
// create a binary tree
struct TreeNode* root = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
// traverse the tree
printf("In-order traversal: ");
traverse(root);
return 0;
}
```
这是一种简单的递归方式,通过先递归访问左子树,再访问当前节点,最后递归访问右子树,实现二叉树的中序遍历。您可以根据需求修改这段代码。
阅读全文