请用C语言编程实现二叉树中序遍历和后续遍历的递归算法和非递归算法,要有菜单
时间: 2024-05-07 09:19:13 浏览: 124
好的,以下是代码实现。注意,这里只提供代码参考,具体实现可能需要根据具体情况进行调整。
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode{
int val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
void createTree(TreeNode** node){
int val;
scanf("%d",&val);
if(val == -1){
*node = NULL;
}else{
*node = (TreeNode*)malloc(sizeof(TreeNode));
(*node)->val = val;
createTree(&((*node)->left));
createTree(&((*node)->right));
}
}
void inOrderRecursive(TreeNode* node){
if(node != NULL){
inOrderRecursive(node->left);
printf("%d ",node->val);
inOrderRecursive(node->right);
}
}
void postOrderRecursive(TreeNode* node){
if(node != NULL){
postOrderRecursive(node->left);
postOrderRecursive(node->right);
printf("%d ",node->val);
}
}
void inOrderNonRecursive(TreeNode* node){
TreeNode* stack[MAXSIZE];
int top = -1;
while(node != NULL || top != -1){
while(node != NULL){
stack[++top] = node;
node = node->left;
}
if(top != -1){
node = stack[top--];
printf("%d ",node->val);
node = node->right;
}
}
}
void postOrderNonRecursive(TreeNode* node){
TreeNode* stack[MAXSIZE];
int top = -1,visited[MAXSIZE] = {0};
while(node != NULL || top != -1){
while(node != NULL){
stack[++top] = node;
node = node->left;
}
if(top != -1){
node = stack[top];
if(visited[node->val]){
printf("%d ",node->val);
top--;
node = NULL;
}else{
visited[node->val] = 1;
node = node->right;
}
}
}
}
int main(){
TreeNode* root = NULL;
int choice;
while(1){
printf("\n1. Create binary tree\n");
printf("2. Inorder recursive traversal\n");
printf("3. Postorder recursive traversal\n");
printf("4. Inorder non-recursive traversal\n");
printf("5. Postorder non-recursive traversal\n");
printf("6. Exit\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter tree in preorder: ");
createTree(&root);
break;
case 2:
printf("Inorder recursive traversal: ");
inOrderRecursive(root);
printf("\n");
break;
case 3:
printf("Postorder recursive traversal: ");
postOrderRecursive(root);
printf("\n");
break;
case 4:
printf("Inorder non-recursive traversal: ");
inOrderNonRecursive(root);
printf("\n");
break;
case 5:
printf("Postorder non-recursive traversal: ");
postOrderNonRecursive(root);
printf("\n");
break;
case 6:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
```
菜单功能:
1. 创建二叉树
2. 二叉树中序遍历的递归算法
3. 二叉树后续遍历的递归算法
4. 二叉树中序遍历的非递归算法
5. 二叉树后续遍历的非递归算法
6. 退出程序
阅读全文