重建二叉樹 C語言實現

2021-06-19 02:40:55 字數 1099 閱讀 7178

主要根據程式設計之美中利用前序與中序遍歷實現二叉樹的重構。其中對於前序遍歷中的每乙個節點都是當前子樹的根節點這一理論來對中序遍歷進行劃分。

並且也實現了根據中序遍歷與後序遍歷實現二叉樹的重構,其中對於後序遍歷主要要注意其中後序遍歷的最後乙個元素表示的是根節點這一思想來實現。其中對於利用前序遍歷與中序遍歷實現二叉樹的重構的演算法思想可以參考部落格主要實現**如下:

#include #include #include #include typedef char status;

typedef struct node

node;

/*利用前序遍歷與中序遍歷重構二叉樹*/

void rebulid(status *ppreorder,status *pinorder,int len,node **proot)

leftnum=(int)(pleft-porginorder);

rightnum=(int)(len-leftnum-1);

if (leftnum>0)

rebulid(ppreorder+1,pinorder,leftnum,&((*proot)->left));

if (rightnum>0)

rebulid(ppreorder+leftnum+1,pinorder+leftnum+1,rightnum,&((*proot)->right));

}/*利用中序遍歷與後序遍歷重構二叉樹*/

void rebulid1(status *ppostorder,status *pinorder,int len,node **proot)

leftnum=(int)(pinleft-porginorder);

rightnum=len-leftnum-1;

if (leftnum>0)

rebulid1(ppostorder,pinorder,leftnum,&((*proot)->left));

if (rightnum>0)

rebulid1(ppostorder+leftnum,pinorder+leftnum+1,rightnum,&((*proot)->right));

}int main()

C語言實現二叉樹

1.c語言實現二叉樹中節點間最大距離 includetypedef struct treenode treenode 我們可以將所有的結點的左右子樹的高度和計算一下,然後取出最大值,就是最遠的距離。int getmaxdistance treenode root,int maxdistance in...

二叉樹(C語言實現)

以下為用c語言實現的二叉排序樹,包含了樹的建立,銷毀,新增,刪除,修改,前 中 後 層序遍歷,深度,密度。include include include define type int typedef struct node node 建立結點 node creat node type data 新...

C語言實現構建二叉樹

include include include typedef int elemtype typedef struct btreebt,b tree 增加新節點 brief insert node param root param nodevalue return b tree insert nod...