中序遍历
一、实例要求
- 给定一个二叉树的
根节点 root
,返回 它的中序 遍历
;
二、实例分析
- 1、首先定义了二叉树的结构 TreeNode,以及栈的结构 Stack 和相关操作;
- 2、然后实现了中序遍历函数 inorderTraversal,在遍历过程中使用栈来辅助实现;
- 3、最后释放了内存;
三、示例代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// 定义栈的结构和相关操作
struct StackNode {
struct TreeNode *node;
struct StackNode *next;
};
struct Stack {
struct StackNode *top;
};
void stackPush(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 *stackPop(struct Stack *stack) {
if (stack->top == NULL) {
return NULL;
}
struct TreeNode *node = stack->top->node;
struct StackNode *temp = stack->top;
stack->top = stack->top->next;
free(temp);
return node;
}
int isStackEmpty(struct Stack *stack) {
return (stack->top == NULL);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
// 创建一个用于存储遍历结果的数组
int *result = (int *)malloc(100 * sizeof(int));
*returnSize = 0;
// 创建一个栈
struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
stack->top = NULL;
// 遍历二叉树
while (root != NULL || !isStackEmpty(stack)) {
// 将当前节点及其左子节点依次入栈
while (root != NULL) {
stackPush(stack, root);
root = root->left;
}
// 弹出栈顶节点,访问该节点的值,并将其右子节点设为当前节点
root = stackPop(stack);
result[(*returnSize)++] = root->val;
root = root->right;
}
// 释放栈内存
free(stack);
return result;
}
四、运行结果