本帖最后由 wuliangtdi 于 2023-4-18 17:20 编辑
C语言版
先定义一些内容:typedef struct StackNode {
void* data;
struct StackNode* next;
} StackNode;
typedef struct Stack {
StackNode* top;
int size;
} Stack;
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
stack->size = 0;
return stack;
}
void destroyStack(Stack* stack) {
if (stack == NULL) return;
while (!isEmpty(stack)) {
StackNode* node = stack->top;
stack->top = stack->top->next;
free(node);
stack->size--;
}
free(stack);
}
bool isEmpty(Stack* stack) {
return stack->top == NULL;
}
void push(Stack* stack, void* data) {
StackNode* node = (StackNode*)malloc(sizeof(StackNode));
node->data = data;
node->next = stack->top;
stack->top = node;
stack->size++;
}
void* pop(Stack* stack) {
if (isEmpty(stack)) return NULL;
StackNode* node = stack->top;
void* data = node->data;
stack->top = stack->top->next;
free(node);
stack->size--;
return data;
}
前序遍历:void preorderTraversal(TreeNode* root) {
if (root == NULL) return;
Stack* stack = createStack();
push(stack, root);
while (!isEmpty(stack)) {
TreeNode* node = (TreeNode*)pop(stack);
printf("%d ", node->val);
if (node->right != NULL) push(stack, node->right);
if (node->left != NULL) push(stack, node->left);
}
destroyStack(stack);
}
中序遍历:void inorderTraversal(TreeNode* root) {
if (root == NULL) return;
Stack* stack = createStack();
TreeNode* node = root;
while (!isEmpty(stack) || node != NULL) {
if (node != NULL) {
push(stack, node);
node = node->left;
} else {
node = (TreeNode*)pop(stack);
printf("%d ", node->val);
node = node->right;
}
}
destroyStack(stack);
}
后序遍历:void postorderTraversal(TreeNode* root) {
if (root == NULL) return;
Stack* stack1 = createStack();
Stack* stack2 = createStack();
push(stack1, root);
while (!isEmpty(stack1)) {
TreeNode* node = (TreeNode*)pop(stack1);
push(stack2, node);
if (node->left != NULL) push(stack1, node->left);
if (node->right != NULL) push(stack1, node->right);
}
while (!isEmpty(stack2)) {
TreeNode* node = (TreeNode*)pop(stack2);
printf("%d ", node->val);
}
destroyStack(stack1);
destroyStack(stack2);
}
|