二叉树先序遍历用goto语句实现
时间: 2023-11-23 16:08:10 浏览: 68
二叉树的先序遍历可以使用递归或非递归的方式实现,使用`goto`语句也可以完成。以下是使用`goto`语句实现二叉树先序遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct TreeNode* stack[1000]; // 定义一个栈用于存储待访问的节点
int top = -1; // 栈顶指针初始化为-1
struct TreeNode* node = root;
while (1) {
while (node != NULL) {
printf("%d ", node->val); // 访问当前节点的值
stack[++top] = node; // 将当前节点入栈
node = node->left; // 继续遍历左子树
}
if (top != -1) {
node = stack[top--]; // 弹出栈顶节点
node = node->right; // 遍历右子树
} else {
break;
}
}
}
int main() {
// 构建一个二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node1 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node2 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node3 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node4 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
node1->val = 2;
node2->val = 3;
node3->val = 4;
node4->val = 5;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = NULL;
node2->left = node4;
node2->right = NULL;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
// 先序遍历二叉树
printf("Preorder traversal:\n");
preorderTraversal(root);
// 释放内存
free(node4);
free(node3);
free(node2);
free(node1);
free(root);
return 0;
}
```
阅读全文