二叉树:
1 #include <stdlib.h> 2 #include <string.h> 3 #include <stdio.h> 4 5 6 typedef struct BIT_NODE { 7 char data; 8 struct BIT_NODE* lchild; 9 struct BIT_NODE* rchild; 10 }BIT_NODE_t; 11 12 // 先序遍历 13 void pre_travel(BIT_NODE_t root) 14 { 15 printf("%c ", root.data); 16 17 if (root.lchild != NULL) { 18 pre_travel(*root.lchild); 19 } 20 if (root.rchild != NULL) { 21 pre_travel(*root.rchild); 22 } 23 24 } 25 26 // 中序遍历 27 void mid_travel(BIT_NODE_t root) 28 { 29 if (root.lchild != NULL) { 30 mid_travel(*root.lchild); 31 } 32 printf("%c ", root.data); 33 if (root.rchild != NULL) { 34 mid_travel(*root.rchild); 35 } 36 } 37 38 // 后序 39 void after_travel(BIT_NODE_t root) 40 { 41 if (root.lchild != NULL) { 42 after_travel(*root.lchild); 43 } 44 if (root.rchild != NULL) { 45 after_travel(*root.rchild); 46 } 47 printf("%c ", root.data); 48 } 49 50 int main() 51 { 52 BIT_NODE_t NodeA, NodeB, NodeC, NodeD, NodeE, NodeF, NodeG; 53 54 memset(&NodeA, 0, sizeof(BIT_NODE_t)); 55 memset(&NodeB, 0, sizeof(BIT_NODE_t)); 56 memset(&NodeC, 0, sizeof(BIT_NODE_t)); 57 memset(&NodeD, 0, sizeof(BIT_NODE_t)); 58 memset(&NodeE, 0, sizeof(BIT_NODE_t)); 59 memset(&NodeF, 0, sizeof(BIT_NODE_t)); 60 memset(&NodeG, 0, sizeof(BIT_NODE_t)); 61 62 NodeA.data = 'A'; 63 NodeA.lchild = &NodeB; 64 NodeA.rchild = &NodeC; 65 66 NodeB.data = 'B'; 67 NodeB.lchild = &NodeD; 68 NodeB.rchild = &NodeE; 69 70 NodeC.data = 'C'; 71 NodeC.lchild = &NodeF; 72 NodeC.rchild = &NodeG; 73 74 NodeD.data = 'D'; 75 NodeE.data = 'E'; 76 NodeF.data = 'F'; 77 NodeG.data = 'G'; 78 79 // 先序遍历 80 //pre_travel(NodeA); 81 82 // mmid 83 //mid_travel(NodeA); 84 85 // after 86 after_travel(NodeA); 87 88 system("pause"); 89 return 0; 90 }
叶子节点:没有左孩子也没有右孩子
叶子节点的个数 = 左子树叶子节点个数 + 右子树叶子节点个数
1 // 求树的叶子节点数 2 void leaf_num(BIT_NODE_t root, int* num) 3 { 4 5 if ( root.lchild == NULL && root.rchild == NULL ) { 6 (*num)++; 7 } 8 if ( root.lchild != NULL ) { 9 leaf_num(*root.lchild, num); 10 } 11 if (root.rchild != NULL) { 12 leaf_num(*root.rchild, num); 13 } 14 15 }
树的高度 :
1.求根节点左子树的高度,再求根节点右子树的高度,比较子树的最大高度再加 1;
2.若左子树还是树,重复步骤1;若右子树还是树,重复步骤1
1 // 求树的高度 2 int tree_depth(BIT_NODE_t root) 3 { 4 int left = 0; 5 int right = 0; 6 if (root.lchild != NULL) { 7 left = tree_depth(*root.lchild); 8 } 9 if (root.rchild != NULL) { 10 right = tree_depth(*root.rchild); 11 } 12 int max = left > right ? left : right; 13 return max + 1; 14 }
拷贝二叉树
1 // 拷贝二叉树 返回新二叉树的根节点 2 BIT_NODE_t* copy_tree(BIT_NODE_t *root) 3 { 4 if (root == NULL) { 5 return NULL; 6 } 7 BIT_NODE_t* left = copy_tree(root->lchild); 8 BIT_NODE_t* right = copy_tree(root->rchild); 9 10 BIT_NODE_t* new_node = (BIT_NODE_t*)malloc(sizeof(BIT_NODE_t)); 11 new_node->data = root->data; 12 new_node->lchild = left; 13 new_node->rchild = right; 14 15 return new_node; 16 }
树的非递归遍历 (中序遍历)
创建树:
1.根据先序和中序可以创建树
2.井号法创建树(先序遍历的方式)