使用栈实现C语言中二叉树的前序遍历(非递归)可以按照以下方式进行:

#include <stdio.h>
#include <stdlib.h>

// 二叉树节点的定义
struct TreeNode {
    int data;
    struct TreeNode* left;
    struct TreeNode* right;
};

// 栈节点的定义
struct StackNode {
    struct TreeNode* node;
    struct StackNode* next;
};

// 栈的定义
struct Stack {
    struct StackNode* top;
};

// 初始化栈
void initStack(struct Stack* stack) {
    stack->top = NULL;
}

// 判断栈是否为空
int isEmpty(struct Stack* stack) {
    return (stack->top == NULL);
}

// 将节点入栈
void push(struct Stack* stack, struct TreeNode* node) {
    struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
    newNode->node = node;
    newNode->next = stack->top;
    stack->top = newNode;
}

// 将栈顶节点出栈
struct TreeNode* pop(struct Stack* stack) {
    if (isEmpty(stack)) {
        return NULL;
    }
    struct StackNode* temp = stack->top;
    stack->top = stack->top->next;
    struct TreeNode* poppedNode = temp->node;
    free(temp);
    return poppedNode;
}

// 前序遍历二叉树(非递归)
void preOrderTraversal(struct TreeNode* root) {
    if (root == NULL) {
        return;
    }

    struct Stack stack;
    initStack(&stack);

    push(&stack, root);

    while (!isEmpty(&stack)) {
        struct TreeNode* current = pop(&stack);
        printf("%d ", current->data);

        // 注意:由于栈是先进后出的结构,所以先将右子树入栈,再将左子树入栈
        if (current->right != NULL) {
            push(&stack, current->right);
        }
        if (current->left != NULL) {
            push(&stack, current->left);
        }
    }
}

// 测试
int main() {
    // 构建一个简单的二叉树
    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->data = 1;
    root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->left->data = 2;
    root->left->left = NULL;
    root->left->right = NULL;
    root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->right->data = 3;
    root->right->left = NULL;
    root->right->right = NULL;

    // 进行前序遍历
    printf("前序遍历结果: ");
    preOrderTraversal(root);

    return 0;
}

这段代码实现了使用栈进行非递归的二叉树前序遍历。

2024香港开奖结果一览表 澳奖码开奖网站一肖