二叉树的前序遍历C++实现代码
时间: 2023-06-03 11:01:53 浏览: 116
满二叉树的前序遍历C++实现
以下是二叉树的前序遍历C实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
void preOrder(TreeNode* root) {
if(root == NULL)
return;
printf("%d ", root -> val);
preOrder(root -> left);
preOrder(root -> right);
}
int main() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root -> val = 1;
root -> left = (TreeNode*)malloc(sizeof(TreeNode));
root -> left -> val = 2;
root -> left -> left = NULL;
root -> left -> right = NULL;
root -> right = (TreeNode*)malloc(sizeof(TreeNode));
root -> right -> val = 3;
root -> right -> left = (TreeNode*)malloc(sizeof(TreeNode));
root -> right -> left -> val = 4;
root -> right -> left -> left = NULL;
root -> right -> left -> right = NULL;
root -> right -> right = (TreeNode*)malloc(sizeof(TreeNode));
root -> right -> right -> val = 5;
root -> right -> right -> left = NULL;
root -> right -> right -> right = NULL;
preOrder(root);
return 0;
}
```
这是一个简单的二叉树数据结构,使用前序遍历方法输出树的节点值。前序遍历的顺序是:先遍历根节点,再遍历左子树,最后遍历右子树。在这个实现中,我们使用了递归来遍历二叉树。
阅读全文