本程序实际上是构建了一颗二叉排序树,程序最后输出构建数的中序遍历。
代码实现:
#include <stdio.h> #include <stdlib.h> // Author: 过往记忆 // Email: wyphao.2007@163.com // Blog: typedef int DataType; typedef struct BTree{ DataType data; struct BTree *Tleft; struct BTree *Tright; }*BTree; BTree CreateTree(); BTree insert(BTree root, DataType data); void InBTree(BTree root); int main(){ BTree root = NULL; root = CreateTree(); InBTree(root); printf("\n"); return 0; } BTree CreateTree(){ BTree root = NULL; DataType temp = 0; printf("Input data, if you want to exit, please input 0:\n"); scanf("%d", &temp); while(temp != 0){ root = insert(root, temp); scanf("%d", &temp); } return root; } BTree insert(BTree root, DataType data){ BTree ptr = root; BTree tempNode; BTree newNode = (BTree)malloc(sizeof(struct BTree)); newNode->data = data ; newNode->Tleft = NULL; newNode->Tright = NULL; if(ptr == NULL){ return newNode; }else{ while(ptr != NULL){ tempNode = ptr; if(ptr->data >= data){ ptr = ptr->Tleft; }else{ ptr = ptr->Tright; } } if(tempNode->data >= data){ tempNode->Tleft = newNode; }else{ tempNode->Tright = newNode; } } return root; } void InBTree(BTree root){ if(root != NULL){ InBTree(root->Tleft); printf("%d ", root->data); InBTree(root->Tright); } }本博客文章除特别声明,全部都是原创!
原创文章版权归过往记忆大数据(过往记忆)所有,未经许可不得转载。
本文链接: 【二叉树的链表表示法实现】(https://www.iteblog.com/archives/192.html)