1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef char TelemType; 4 5 typedef struct BinTree{ 6 TelemType data; 7 struct BinTree *LChild; 8 struct BinTree *RChild; 9 }BinaryTree; 10 11 // 12 13 14 BinaryTree* create_BinaryTree(BinaryTree *T) 15 { 16 TelemType tmp; 17 scanf("%c", &tmp); 18 if(tmp == ‘0‘) 19 return 0; 20 21 T = (BinaryTree*)malloc(sizeof(BinaryTree)); 22 T->data = tmp; 23 T->LChild = create_BinaryTree(T->LChild); 24 T->RChild = create_BinaryTree(T->RChild); 25 return T; 26 } 27 28 // 计算叶子节点的个数 29 int sum_left(BinaryTree *T) 30 { 31 int sum = 0, lnum, rnum; 32 if(T) 33 { 34 if((!T->LChild) && (!T->RChild)) 35 { 36 sum++; 37 } 38 lnum = sum_left(T->LChild); 39 sum += lnum; 40 rnum = sum_left(T->RChild); 41 sum += rnum; 42 } 43 return sum; 44 } 45 46 void preorder_traverse(BinaryTree *T) 47 { 48 if(T) 49 { 50 printf("%c ", T->data); 51 preorder_traverse(T->LChild); 52 preorder_traverse(T->RChild); 53 } 54 } 55 56 void inorder_traverse(BinaryTree *T) 57 { 58 if(T) 59 { 60 inorder_traverse(T->LChild); 61 printf("%c ", T->data); 62 inorder_traverse(T->RChild); 63 } 64 } 65 66 void postorder_traverse(BinaryTree *T) 67 { 68 if(T) 69 { 70 postorder_traverse(T->LChild); 71 postorder_traverse(T->RChild); 72 printf("%c ", T->data); 73 } 74 } 75 76 77 BinaryTree* get_tree_node(TelemType item, BinaryTree *ltree, BinaryTree *rtree) 78 { 79 BinaryTree *T; 80 T = (BinaryTree*)malloc(sizeof(BinaryTree)); 81 T->data = item; 82 T->LChild = ltree; 83 T->RChild = rtree; 84 return T; 85 } 86 87 BinaryTree* copy_tree(BinaryTree *T) 88 { 89 if(!T) 90 return NULL; 91 BinaryTree *newltree, *newrtree, *newT; 92 if(T->LChild) 93 newltree = copy_tree(T->LChild); 94 else 95 newltree = NULL; 96 if(T->RChild) 97 newrtree = copy_tree(T->RChild); 98 else 99 newrtree = NULL; 100 newT = get_tree_node(T->data, newltree, newrtree); 101 return newT; 102 } 103 104 int max(int n1, int n2) 105 { 106 return (n1 > n2) ? n1 : n2; 107 } 108 109 int get_deep(BinaryTree *T) 110 { 111 int dep = 0, ldep, rdep; 112 if(!T) 113 dep = 0; 114 else 115 { 116 ldep = get_deep(T->LChild); 117 rdep = get_deep(T->RChild); 118 dep = 1 + max(ldep, rdep); 119 } 120 } 121 122 int main() 123 { 124 BinaryTree *bin_tree, *tree; 125 bin_tree = create_BinaryTree(bin_tree); 126 printf("+++++++++++++++++++++++++++++\n"); 127 preorder_traverse(bin_tree); 128 puts(""); 129 inorder_traverse(bin_tree); 130 puts(""); 131 postorder_traverse(bin_tree); 132 puts(""); 133 printf("叶子节点个数%d\n", sum_left(bin_tree)); 134 printf("树的深度是%d\n", get_deep(bin_tree)); 135 tree = copy_tree(bin_tree); 136 preorder_traverse(tree); 137 return 0; 138 }
写在博客上,然后就要开始手写了~~~~~
时间: 2024-12-23 21:26:31