实现了二叉树类似链表的一种结构,主要是用两个函数进行添加左右节点,同时每次添加都返回新加上的节点地址,我觉得应该可以进行递归式的动态添加,但是我没有实现。
下面是最简单的二叉树的一些实现操作。
BinaryTree.cpp
1 #include "iostream" 2 #include "stdlib.h" 3 4 typedef struct _btree_ 5 { 6 char *data; 7 struct _btree_ *leftTree; 8 struct _btree_ *rightTree; 9 }BTree; 10 11 /*初始化根节点,返回的是根节点地址*/ 12 BTree* 13 initRoot(char *data) 14 { 15 BTree *root = (BTree *)malloc(sizeof(BTree)); 16 root->data = data; 17 root->leftTree = nullptr; 18 root->rightTree = nullptr; 19 return root; 20 } 21 22 /*添加左节点,并返回加入的左节点的地址*/ 23 BTree* 24 addLeft(BTree *father, char *data) 25 { 26 BTree *p = (BTree *)malloc(sizeof(BTree)); 27 p->data = data; 28 p->leftTree = nullptr; 29 p->rightTree = nullptr; 30 father->leftTree = p; 31 return p; 32 } 33 34 /*添加右节点,并返回加入的右节点的地址*/ 35 BTree* 36 addRight(BTree *father, char *data) 37 { 38 BTree *p = (BTree *)malloc(sizeof(BTree)); 39 p->data = data; 40 p->leftTree = nullptr; 41 p->rightTree = nullptr; 42 father->rightTree = p; 43 return p; 44 } 45 46 /*打印出所有节点的数据*/ 47 void 48 printOut(BTree *root) 49 { 50 if (root) 51 std::cout << root->data << std::endl; 52 else 53 return; 54 if (root->leftTree) 55 { 56 printOut(root->leftTree); 57 } 58 if (root->rightTree) 59 { 60 printOut(root->rightTree); 61 } 62 } 63 64 int main(void) 65 { 66 BTree *root = nullptr; 67 BTree *left = nullptr; 68 BTree *right = nullptr; 69 root = initRoot("root"); 70 left=addLeft(root, "left"); 71 right=addRight(root, "right"); 72 addLeft(left, "A"); 73 addRight(left, "B"); 74 addLeft(right, "C"); 75 addRight(right, "D"); 76 printOut(root); 77 system("pause"); 78 return 0; 79 }
打印操作没有进行严格测试,如果读者发现错误希望不吝赐教,不胜感激。
以上。
时间: 2024-10-12 23:07:08