用c语言写一个双向二叉树
时间: 2024-04-25 12:22:03 浏览: 130
双向二叉树是一种特殊的二叉树,每个节点除了有左子节点和右子节点外,还有一个指向父节点的指针。以下是用C语言实现一个双向二叉树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
struct Node* parent;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
newNode->parent = NULL;
return newNode;
}
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
} else {
struct Node* temp;
if (data <= root->data) {
temp = insert(root->left, data);
root->left = temp;
temp->parent = root;
} else {
temp = insert(root->right, data);
root->right = temp;
temp->parent = root;
}
return root;
}
}
void inOrder(struct Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}
int main() {
struct Node* root = NULL;
int n, data;
printf("请输入元素个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d个元素:", i+1);
scanf("%d", &data);
root = insert(root, data);
}
printf("中序遍历结果:");
inOrder(root);
return 0;
}
```
这段代码实现了一个双向二叉树的创建和中序遍历。用户可以输入元素个数和具体的元素值,程序会根据输入构建一个双向二叉树,并输出中序遍历的结果。
#### 引用[.reference_title]
- *1* *2* *3* [c语言写一个简单的二叉树](https://blog.csdn.net/qq_51838257/article/details/115574679)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文