使用c++语言实现二叉链类,完成以下功能: 根据括号表示法字符串构造二叉链 由二叉链输出二叉树(括号表示法) 翻转二叉树
时间: 2023-06-11 10:08:02 浏览: 130
以下是使用C语言实现二叉链类的代码,并完成了所述功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
char data; // 数据
struct TreeNode* left; // 左子树指针
struct TreeNode* right; // 右子树指针
} TreeNode;
// 栈结构体
typedef struct Stack {
TreeNode** array; // 栈数组
int top; // 栈顶指针
int capacity; // 栈容量
} Stack;
// 初始化栈
Stack* initStack(int capacity) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->array = (TreeNode**)malloc(sizeof(TreeNode*) * capacity);
stack->top = -1;
stack->capacity = capacity;
return stack;
}
// 判断栈是否为空
int isStackEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isStackFull(Stack* stack) {
return stack->top == stack->capacity - 1;
}
// 入栈
void push(Stack* stack, TreeNode* node) {
if (isStackFull(stack)) {
return;
}
stack->array[++stack->top] = node;
}
// 出栈
TreeNode* pop(Stack* stack) {
if (isStackEmpty(stack)) {
return NULL;
}
return stack->array[stack->top--];
}
// 获取栈顶元素
TreeNode* peek(Stack* stack) {
if (isStackEmpty(stack)) {
return NULL;
}
return stack->array[stack->top];
}
// 根据括号表示法字符串构造二叉链
TreeNode* buildBinaryTree(char* s) {
Stack* stack = initStack(100);
TreeNode* root = NULL;
int i = 0;
while (s[i]) {
if (s[i] == '(') {
push(stack, root);
root = NULL;
} else if (s[i] == ')') {
root = pop(stack);
} else if (s[i] >= 'a' && s[i] <= 'z') {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = s[i];
node->left = NULL;
node->right = NULL;
if (root == NULL) {
root = node;
} else {
if (root->left == NULL) {
root->left = node;
} else {
root->right = node;
}
}
}
i++;
}
return root;
}
// 由二叉链输出二叉树(括号表示法)
void printBinaryTree(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c", root->data);
if (root->left != NULL || root->right != NULL) {
printf("(");
printBinaryTree(root->left);
if (root->right != NULL) {
printf(",");
printBinaryTree(root->right);
}
printf(")");
}
}
// 翻转二叉树
void reverseBinaryTree(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
reverseBinaryTree(root->left);
reverseBinaryTree(root->right);
}
int main() {
char s[] = "a(b(d,e),c(f,g))";
TreeNode* root = buildBinaryTree(s);
printf("Original binary tree in bracket representation: ");
printBinaryTree(root);
printf("\n");
printf("Reversed binary tree in bracket representation: ");
reverseBinaryTree(root);
printBinaryTree(root);
printf("\n");
return 0;
}
```
其中,`buildBinaryTree()`函数根据括号表示法字符串构造二叉链;`printBinaryTree()`函数由二叉链输出二叉树(括号表示法);`reverseBinaryTree()`函数翻转二叉树。可以通过修改`char s[]`的值来构造不同的二叉树。
阅读全文