数据结构-二叉树
1 #include "stdio.h" 2 #include "stdlib.h" 3 #include "string.h" 4 typedef char DataType; 5 typedef struct BinTree{ 6 DataType key; //数据存放 7 struct BinTree *left; //左孩子 8 struct BinTree *right; //右孩子 9 }BinTree; 10 int count = 0; 11 int nullChildCount = 0; 12 BinTree *createBinTree() 13 { 14 DataType ch; 15 BinTree *T; 16 17 ch = getchar(); 18 getchar(); //接收输入的回车符 19 if(ch!='#')//输入'#'代表空节点 20 { 21 count++; 22 T=(BinTree*)malloc(sizeof(BinTree)); //创建节点 23 T->key=ch; 24 T->left=createBinTree(); 25 T->right=createBinTree(); 26 } 27 else 28 { 29 T=NULL; 30 } 31 return T; 32 } 33 //按广义表先序输出 34 void BinTreePrint(BinTree *t) 35 { 36 printf("%c",t->key); 37 if(t->left != NULL) 38 { 39 printf("("); 40 BinTreePrint(t->left); 41 } 42 if(t->right != NULL) 43 { 44 if(t->left == NULL) 45 { 46 printf("("); 47 } 48 printf(","); 49 BinTreePrint(t->right); 50 printf(")"); 51 } 52 } 53 //输出叶子节点,就是输出没有左节点和右节点的节点 54 void nullChildNodePrint(BinTree *t) 55 { 56 57 if(t == NULL) 58 { 59 return ; 60 } 61 if(t->left == NULL && t->right == NULL) 62 { 63 printf("%c\t",t->key); 64 nullChildCount++; 65 } 66 nullChildNodePrint(t->left); 67 nullChildNodePrint(t->right); 68 } 69 //获得树的高度 70 int getHeight(BinTree *t) 71 { 72 if(t == NULL) 73 { 74 return 0; 75 } 76 int leftHeight = getHeight(t->left); 77 int rightHeight = getHeight(t->right); 78 return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1; 79 } 80 //得到输入的节点的双亲节点 81 BinTree *getParent(BinTree *t, DataType key) 82 {2 83 if((t->left != NULL && t->left->key == key) ||(t->right !=NULL && t->right->key == key)) 84 { 85 return t; 86 } 87 else 88 { 89 getParent(t->left, key); 90 getParent(t->right, key); 91 } 92 return NULL; 93 94 } 95 //得到输入的节点 96 BinTree *getNode(BinTree *t, DataType key) 97 { 98 if( t != NULL && t->key == key ) 99 { 100 return t; 101 } 102 else 103 { 104 getNode(t->left, key); 105 getNode(t->right, key); 106 } 107 return NULL; 108 } 109 main() 110 { 111 BinTree *t; 112 BinTree *temp; 113 BinTree *Parent; 114 DataType key; 115 BinTree *leftChild; 116 BinTree *rightChild; 117 t = createBinTree(); 118 BinTreePrint(t); 119 printf("\n"); 120 int height = getHeight(t); 121 printf("该二叉树的高度为:%d\n",height); 122 printf("该二叉树的有效数据个数为:%d\n",count); 123 printf("该二叉树的叶子节点分别为:\n",count); 124 nullChildNodePrint(t); 125 printf("\n"); 126 printf("该二叉树的叶子节点个数有:%d\n",nullChildCount); 127 printf("请输入您需要查找该节点的双亲节点的的节点:"); 128 scanf("%c",&key); 129 getchar(); 130 Parent = getParent(t, key); 131 printf("您输入的节点的父节点的数据是:%c\n",Parent->key); 132 printf("请输入您需要查找的节点:"); 133 scanf("%c",&key); 134 getchar(); 135 temp = getNode(t, key); 136 leftChild = temp->left; 137 rightChild = temp->right; 138 printf("您输入的节点的左孩子节点数据是:%c",leftChild->key); 139 printf("您输入的节点的右孩子节点数据是:%c",rightChild->key); 140 }