如果你想要避免使用递归来实现树的遍历,我们可以使用迭代的方法。这里以二叉树的中序遍历为例,介绍如何不使用递归来实现遍历。
中序遍历(迭代方法)
对于中序遍历,我们可以使用栈来模拟递归过程的执行。基本思路是:
- 从根节点开始,尽可能地将其所有左子节点压入栈。
- 当无法继续时,弹出栈顶元素,访问之。
- 转向访问该元素的右子节点,重复步骤1和2,直到栈为空且当前节点为空。
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int value;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct StackNode {
TreeNode *tNode;
struct StackNode *next;
} StackNode;
void push(StackNode **top, TreeNode *node) {
StackNode *newNode = (StackNode *)malloc(sizeof(StackNode));
newNode->tNode = node;
newNode->next = *top;
*top = newNode;
}
TreeNode* pop(StackNode **top) {
if (*top == NULL) return NULL;
StackNode *temp = *top;
TreeNode *node = temp->tNode;
*top = temp->next;
free(temp);
return node;
}
int isStackEmpty(StackNode *top) {
return top == NULL;
}
void inorderTraversal(TreeNode *root) {
StackNode *stack = NULL;
TreeNode *current = root;
while (!isStackEmpty(stack) || current != NULL) {
// Push all the left children, if any
while (current != NULL) {
push(&stack, current);
current = current->left;
}
// Current is NULL at this point
current = pop(&stack);
printf("%d ", current->value); // Visit the node
// Now, let's deal with the right child
current = current->right;
}
}
这段代码通过迭代而不是递归来实现了中序遍历,利用栈来保持遍历的状态。这种方法避免了递归可能导致的栈溢出问题,特别适合于处理深度很大的树。