使用C语言和数据结构来编写代码
时间: 2023-07-25 13:20:07 浏览: 116
好的,下面是使用C语言和数据结构来编写交换二叉树中每个节点左右孩子位置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义栈结构体
typedef struct Stack {
TreeNode** data;
int top;
int size;
} Stack;
// 初始化栈
Stack* initStack(int size) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->data = (TreeNode**)malloc(sizeof(TreeNode*) * size);
stack->top = -1;
stack->size = size;
return stack;
}
// 判断栈是否为空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFull(Stack* stack) {
return stack->top == stack->size - 1;
}
// 入栈
void push(Stack* stack, TreeNode* node) {
if (isFull(stack)) {
return;
}
stack->top++;
stack->data[stack->top] = node;
}
// 出栈
TreeNode* pop(Stack* stack) {
if (isEmpty(stack)) {
return NULL;
}
TreeNode* node = stack->data[stack->top];
stack->top--;
return node;
}
// 交换二叉树中每个节点左右孩子位置
TreeNode* invertTree(TreeNode* root) {
if (!root) {
return NULL;
}
Stack* stack = initStack(1000);
push(stack, root);
TreeNode* prev = NULL;
while (!isEmpty(stack)) {
TreeNode* node = stack->data[stack->top];
if ((!node->left && !node->right) || (prev && (node->left == prev || node->right == prev))) {
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
pop(stack);
}
else {
if (node->right) {
push(stack, node->right);
}
if (node->left) {
push(stack, node->left);
}
}
prev = node;
}
return root;
}
// 构建二叉树
TreeNode* buildTree() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
TreeNode* node1 = (TreeNode*)malloc(sizeof(TreeNode));
node1->val = 2;
TreeNode* node2 = (TreeNode*)malloc(sizeof(TreeNode));
node2->val = 3;
TreeNode* node3 = (TreeNode*)malloc(sizeof(TreeNode));
node3->val = 4;
TreeNode* node4 = (TreeNode*)malloc(sizeof(TreeNode));
node4->val = 5;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
node2->left = NULL;
node2->right = NULL;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
return root;
}
// 后序遍历二叉树
void postorder(TreeNode* root) {
if (!root) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
int main() {
TreeNode* root = buildTree();
root = invertTree(root);
postorder(root);
return 0;
}
```
在上述代码中,我们使用了栈来实现后序遍历,并在遍历时交换每个节点的左右孩子。在 `main` 函数中,我们首先构建了一个二叉树,然后调用 `invertTree` 函数进行左右孩子位置交换,最后再进行后序遍历,验证是否交换成功。
阅读全文