可以用C语言写一个二叉树前序遍历的程序吗
时间: 2023-03-30 13:00:56 浏览: 116
是的,可以使用C语言编写二叉树的前序遍历程序。这可以通过递归或使用循环实现。您可以定义一个函数,该函数处理当前二叉树的根节点,并在递归调用该函数的左右子树之前对当前节点进行访问。如果您使用循环,可以使用栈来模拟递归的过程。
相关问题
用C语言写一个二叉树的前序遍历
我可以提供一个简单的C语言代码来实现二叉树的前序遍历:void preOrder(struct node *root)
{
if (root == NULL)
return;
/* 访问根节点 */
printf("%d ", root->data);
/* 遍历左子树 */
preOrder(root->left);
/* 遍历右子树 */
preOrder(root->right);
}
C语言堆栈实现二叉树前序遍历
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
TreeNode *data[MAXSIZE];
int top;
} Stack;
void init(Stack *stack) {
stack->top = -1;
}
int isEmpty(Stack *stack) {
return stack->top == -1;
}
int isFull(Stack *stack) {
return stack->top == MAXSIZE - 1;
}
void push(Stack *stack, TreeNode *node) {
if (isFull(stack)) {
printf("Stack is full.\n");
return;
}
stack->data[++(stack->top)] = node;
}
TreeNode *pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return NULL;
}
return stack->data[(stack->top)--];
}
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Stack stack;
init(&stack);
push(&stack, root);
while (!isEmpty(&stack)) {
TreeNode *node = pop(&stack);
printf("%c ", node->data);
if (node->right != NULL) {
push(&stack, node->right);
}
if (node->left != NULL) {
push(&stack, node->left);
}
}
}
int main() {
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->data = 'A';
root->left = (TreeNode *) malloc(sizeof(TreeNode));
root->left->data = 'B';
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->data = 'C';
root->right->left = (TreeNode *) malloc(sizeof(TreeNode));
root->right->left->data = 'D';
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->right->data = 'E';
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("Preorder traversal: ");
preOrder(root);
printf("\n");
return 0;
}
```
阅读全文