c 语言 二叉树
#include <stdio.h>
#include <stdlib.h>typedef struct BTNode{int data;struct BTNode *lChild;struct BTNode *rChild;
}BiTNode;//先序創建二叉樹
void CreateBiTree(BiTNode **T)
{int ch;scanf("%d",&ch);if (ch == -1){*T = NULL;return;}else{*T = (BiTNode *)malloc(sizeof(BiTNode));(*T)->data = ch;printf("輸入%d的左子節點:",ch);CreateBiTree(&((*T)->lChild));printf("輸入%d的右子節點:",ch);CreateBiTree((&(*T)->rChild));}return;
}//先序遍歷二叉樹
void PreOrderBiTree(BiTNode *T)
{if (T == NULL){return;}else{printf("%d ",T->data);PreOrderBiTree(T->lChild);PreOrderBiTree(T->rChild);}
}//中序遍歷二叉樹
void MiddleOrderBiTree(BiTNode *T)
{if (T == NULL){return;}else{MiddleOrderBiTree(T->lChild);printf("%d ",T->data);MiddleOrderBiTree(T->rChild);}
}//后續遍歷二叉樹
void PostOrderBiTree(BiTNode *T)
{if (T == NULL){return;}else{PostOrderBiTree(T->lChild);PostOrderBiTree(T->rChild);printf("%d ",T->data);}
}//二叉樹的深度
int TreeDeep(BiTNode *T)
{int deep = 0;if (T != NULL){int leftdeep = TreeDeep(T->lChild);int rightdeep = TreeDeep(T->rChild);deep = leftdeep >= rightdeep?leftdeep+1:rightdeep+1;}return deep;
}//葉子節點個數
int LeafCount(BiTNode *T)
{static int count;if (T != NULL){if (T->lChild == NULL && T->rChild == NULL){count++;}LeafCount(T->lChild);LeafCount(T->rChild);}return count;
}//主函數
int main(int argc,const char *argv[])
{BiTNode *T;int depth,leafCount = 0;printf("請輸入第一個節點的值,-1表示沒有葉節點:\n");CreateBiTree(&T);printf("先序遍歷二叉樹:");PreOrderBiTree(T);printf("\n");printf("中序遍歷二叉樹:");MiddleOrderBiTree(T);printf("\n");printf("后續遍歷二叉樹:");PostOrderBiTree(T);printf("\n");depth = TreeDeep(T);printf("樹的深度為:%d\n",depth);leafCount = LeafCount(T);printf("葉子節點個數:%d\n",leafCount);return 0;
}
總結
- 上一篇: C malloc 用法
- 下一篇: 准确率和召回率