用C语言在原来给定的exp7-2基础上,实现二叉树的中序遍历和后序遍历的递归和非递归算法。要求建立的二叉树如图所示
时间: 2024-11-29 22:36:25 浏览: 11
在C语言中,我们可以使用结构体表示二叉树节点,并分别编写递归和非递归的方式来实现二叉树的中序遍历和后序遍历。首先,我们需要定义一个二叉树节点的结构体:
```c
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
```
接下来,我们分别实现中序遍历、后序遍历的递归版本:
```c
// 中序遍历(递归)
void inorderTraversalRec(TreeNode* root) {
if (root != NULL) {
inorderTraversalRec(root->left);
printf("%d ", root->val); // 先左后根
inorderTraversalRec(root->right);
}
}
// 后序遍历(递归)
void postorderTraversalRec(TreeNode* root) {
if (root != NULL) {
postorderTraversalRec(root->left);
postorderTraversalRec(root->right);
printf("%d ", root->val); // 先右后根
}
}
```
然后是非递归版本,这里我们会使用栈来辅助:
```c
// 中序遍历(非递归)
void inorderTraversalNonRec(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* curr = root;
while (curr != NULL || !s.empty()) {
while (curr != NULL) {
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
printf("%d ", curr->val);
curr = curr->right;
}
}
// 后序遍历(非递归)
void postorderTraversalNonRec(TreeNode* root) {
stack<TreeNode*> s1, s2;
s1.push(root);
TreeNode* curr = NULL;
while (!s1.empty()) {
curr = s1.top();
s1.pop();
if (curr->left == NULL && curr->right == NULL) {
printf("%d ", curr->val);
s2.push(curr);
} else if (curr->right != NULL) {
s1.push(curr->right);
} else {
s1.push(curr->left);
}
}
while (!s2.empty()) {
printf("%d ", s2.top()->val);
s2.pop();
}
}
```
注意:为了使用这些函数,你需要先构建一个像下面这样的二叉树:
```c
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 5;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 2;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 4;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 6;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 7;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 8;
```
阅读全文