C语言二叉树的中序线索化
时间: 2024-03-01 09:45:57 浏览: 77
C语言实现二叉树线索化
中序线索化是将二叉树按照中序遍历的顺序进行线索化,使得每个节点的前驱和后继指针指向其在中序遍历中的前一个和后一个节点。下面是C语言实现二叉树中序线索化的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构
struct TreeNode {
int data;
struct TreeNode* left; struct TreeNode* right;
int leftThread; // 左线索标志
int rightThread; // 右线索标志
};
// 创建新节点
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
newNode->leftThread = 0;
newNode->rightThread = 0;
return newNode;
}
// 中序线索化二叉树
void inorderThread(struct TreeNode* root, struct TreeNode** prev) {
if (root != NULL) {
inorderThread(root->left, prev);
// 处理当前节点的前驱指针
if (root->left == NULL) {
root->left = *prev;
root->leftThread = 1;
}
// 处理前一个节点的后继指针
if (*prev != NULL && (*prev)->right == NULL) {
(*prev)->right = root;
(*prev)->rightThread = 1;
}
*prev = root;
inorderThread(root->right, prev);
}
}
// 中序遍历线索二叉树
void inorderTraversal(struct TreeNode* root) {
struct TreeNode* current = root;
// 找到中序遍历的起始节点
while (current->leftThread == 1) {
current = current->left;
}
while (current != NULL) {
printf("%d ", current->data);
// 如果右指针是线索,则直接跳转到后继节点
if (current->rightThread == 1) {
current = current->right;
} else {
// 否则,找到右子树中的最左节点
current = current->right;
while (current != NULL && current->leftThread == 0) {
current = current->left;
}
}
}
}
int main() {
// 创建二叉树
struct TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
// 中序线索化二叉树
struct TreeNode* prev = NULL;
inorderThread(root, &prev);
// 中序遍历线索二叉树
printf("Inorder traversal of threaded binary tree: ");
inorderTraversal(root);
return 0;
}
```
运行以上代码,将会输出中序线索化后的二叉树的中序遍历结果。
阅读全文