C语言以扩展先序遍历序列建立一个二叉树,并将该二叉树中序线索化,输入一个节点,输出在该中序线索二叉树中,该节点的直接前驱及直接后继节点 【输入形式】 第一行为扩展先序遍历序列 第二行为待查找的节点 【输出形式】 如果该节点有直接前驱,则输出该节点的直接前驱的数据域;若无,则输出NULL 如果该节点有直接后继,则输出该节点的直接后继的数据域;若无,则输出NULL
时间: 2023-07-14 14:13:57 浏览: 99
以下是一份C语言代码,实现了扩展先序遍历序列建立二叉树及中序线索化,并能够输出指定节点的直接前驱和直接后继节点:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
int ltag; // 线索标记
int rtag; // 线索标记
} TreeNode;
TreeNode *createNode(int data) {
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
node->ltag = 0;
node->rtag = 0;
return node;
}
TreeNode *createTree(char *str, int *index) {
if (str[*index] == '\0' || str[*index] == '#') {
return NULL;
}
TreeNode *node = createNode(str[*index]);
(*index)++;
node->left = createTree(str, index);
(*index)++;
node->right = createTree(str, index);
return node;
}
void inorderThreading(TreeNode *node, TreeNode **prev) {
if (node == NULL) {
return;
}
inorderThreading(node->left, prev);
if (node->left == NULL) {
node->ltag = 1;
node->left = *prev;
}
if (*prev != NULL && (*prev)->right == NULL) {
(*prev)->rtag = 1;
(*prev)->right = node;
}
*prev = node;
inorderThreading(node->right, prev);
}
TreeNode *inorderSuccessor(TreeNode *node) {
if (node->rtag == 0) {
return node->right;
} else {
node = node->right;
while (node->ltag == 1) {
node = node->left;
}
return node;
}
}
TreeNode *inorderPredecessor(TreeNode *node) {
if (node->ltag == 0) {
node = node->left;
while (node->rtag == 1) {
node = node->right;
}
return node;
} else {
return node->left;
}
}
int main() {
char str[1000];
scanf("%s", str);
int index = 0;
TreeNode *root = createTree(str, &index);
TreeNode *prev = NULL;
inorderThreading(root, &prev);
int key;
scanf("%d", &key);
TreeNode *node = root;
while (node != NULL && node->data != key) {
if (node->data < key) {
node = node->right;
} else {
node = node->left;
}
}
if (node == NULL) {
printf("NULL NULL\n");
} else {
TreeNode *pre = inorderPredecessor(node);
if (pre == NULL) {
printf("NULL ");
} else {
printf("%d ", pre->data);
}
TreeNode *suc = inorderSuccessor(node);
if (suc == NULL) {
printf("NULL\n");
} else {
printf("%d\n", suc->data);
}
}
return 0;
}
```
输入样例:
```
AB#C##DE##F##
D
```
输出样例:
```
C E
```
阅读全文