c 二叉树的非递归遍历
时间: 2023-11-14 21:25:14 浏览: 82
C语言中,二叉树的非递归遍历同样可以使用栈来实现。以下是三种遍历方式的代码实现:
1. 非递归先序遍历:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void preorderTraversal(struct TreeNode* root) {
struct TreeNode* stack[100];
int top = -1;
if(root != NULL) {
stack[++top] = root;
}
while(top != -1) {
struct TreeNode* node = stack[top--];
printf("%d ", node->val);
if(node->right != NULL) {
stack[++top] = node->right;
}
if(node->left != NULL) {
stack[++top] = node->left;
}
}
}
```
2. 非递归中序遍历:
```c
void inorderTraversal(struct TreeNode* root) {
struct TreeNode* stack[100];
int top = -1;
struct TreeNode* node = root;
while(node != NULL || top != -1) {
while(node != NULL) {
stack[++top] = node;
node = node->left;
}
node = stack[top--];
printf("%d ", node->val);
node = node->right;
}
}
```
3. 非递归后序遍历:
```c
void postorderTraversal(struct TreeNode* root) {
struct TreeNode* stack[100];
int top = -1;
struct TreeNode* node = root;
struct TreeNode* lastNodeVisited = NULL;
while(node != NULL || top != -1) {
while(node != NULL) {
stack[++top] = node;
node = node->left;
}
node = stack[top];
if(node->right == NULL || node->right == lastNodeVisited) {
printf("%d ", node->val);
top--;
lastNodeVisited = node;
node = NULL;
} else {
node = node->right;
}
}
}
```
以上代码中,struct TreeNode是二叉树节点的定义,val表示节点的值,left和right分别表示左子树和右子树。栈的大小可以根据二叉树的大小进行调整。
阅读全文