日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

用c语言编译二叉树,C语言实现二叉树的基本操作

發布時間:2023/12/20 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用c语言编译二叉树,C语言实现二叉树的基本操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我在前面的博客中解說了鏈表、棧和隊列。這些數據結構事實上都是線性表,而且給出了具體的實現。

從今天開始。我們將要來學習樹,樹作為一種數據結構我們常常會用到,作為起步和基礎。我們先來實現二叉樹。也就是每一個節點有不超過2個子節點的樹。對于樹的操作,最主要的創建、遍歷、求樹高、節點數等。代碼上傳至 https://github.com/chenyufeng1991/BinaryTree?。

(1)節點的定義

typedef struct BTNode{

int data;

struct BTNode *lChild;

struct BTNode *rChild;

}BiTNode;

(2)二叉樹的創建

//先序創建二叉樹

int CreateBiTree(BiTNode **T)

{

int ch;

scanf("%d",&ch);

if (ch == -1)

{

*T = NULL;

return 0;

}

else

{

*T = (BiTNode *)malloc(sizeof(BiTNode));

if (T == NULL)

{

printf("failed

");

return 0;

}

else

{

(*T)->data = ch;

printf("輸入%d的左子節點:",ch);

CreateBiTree(&((*T)->lChild));

printf("輸入%d的右子節點:",ch);

CreateBiTree((&(*T)->rChild));

}

}

return 1;

}

(3)先序遍歷二叉樹

//先序遍歷二叉樹

void PreOrderBiTree(BiTNode *T)

{

if (T == NULL)

{

return;

}

else

{

printf("%d ",T->data);

PreOrderBiTree(T->lChild);

PreOrderBiTree(T->rChild);

}

}

(4)中序遍歷二叉樹

//中序遍歷二叉樹

void MiddleOrderBiTree(BiTNode *T)

{

if (T == NULL)

{

return;

}

else

{

MiddleOrderBiTree(T->lChild);

printf("%d ",T->data);

MiddleOrderBiTree(T->rChild);

}

}

(5)興許遍歷二叉樹

//興許遍歷二叉樹

void PostOrderBiTree(BiTNode *T)

{

if (T == NULL)

{

return;

}

else

{

PostOrderBiTree(T->lChild);

PostOrderBiTree(T->rChild);

printf("%d ",T->data);

}

}

(6)二叉樹的深度

//二叉樹的深度

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;

}

(7)葉子節點個數

//葉子節點個數

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;

}

(8)測試函數

//主函數

int main(int argc,const char *argv[])

{

BiTNode *T;

int depth,leafCount = 0;

printf("請輸入第一個節點的值,-1表示沒有葉節點:

");

CreateBiTree(&T);

printf("先序遍歷二叉樹:");

PreOrderBiTree(T);

printf("

");

printf("中序遍歷二叉樹:");

MiddleOrderBiTree(T);

printf("

");

printf("興許遍歷二叉樹:");

PostOrderBiTree(T);

printf("

");

depth = TreeDeep(T);

printf("樹的深度為:%d

",depth);

leafCount = LeafCount(T);

printf("葉子節點個數:%d

",leafCount);

return 0;

}

總結

以上是生活随笔為你收集整理的用c语言编译二叉树,C语言实现二叉树的基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。