c++使用二叉链表表示二叉树,采用递归的方式建立二叉树,并对二叉树进行后序遍历。
时间: 2024-01-23 22:40:54 浏览: 72
以下是一个使用递归方式建立并进行后序遍历的二叉树实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
Node* createNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
Node* buildTree() {
int data;
scanf("%d", &data);
if (data == -1) {
return NULL;
}
Node* root = createNode(data);
printf("Enter the left child of %d: ", data);
root->left = buildTree();
printf("Enter the right child of %d: ", data);
root->right = buildTree();
return root;
}
void postorder(Node* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
Node* root = NULL;
printf("Enter the root node: ");
root = buildTree();
printf("The postorder traversal of the binary tree is: ");
postorder(root);
printf("\n");
return 0;
}
```
阅读全文