鏈式佇列實現樹的層序遍歷

2022-10-10 11:24:12 字數 2495 閱讀 4046

前言:鏈式佇列實現樹的層序遍歷的筆記

#define _crt_secure_no_warnings

#include#include#include#define maxsize 100

#define ok 1

#define error 0

// dim something struct for writting tree's struct;

// tr**el tree via / pre order tr**el / in order tr**el / post order tr**el

// **實現

// 鏈式層序插入

// 鏈式層序輸出結點

typedef int elemtype;

typedef int status;

// 樹相關結點的定義

typedef struct _treenodetreenode, *ptreenode;

typedef struct _sqtreesqtree, *psqtree;

// 鏈佇列用於層次結點遍歷

typedef struct _linknodelinknode, *plinknode;

typedef struct _linkqueuelinkqueue, *plinkqueue;

// 初始化鏈佇列

status initlinkqueue(linkqueue* plinkqueue)

// 佇列先進先出

status push(linkqueue* plinkqueue, treenode* ptreenode)

linknode* pop(linkqueue* plinkqueue)

status checkqueueempty(linkqueue* plinkqueue)

// get tree's depth

elemtype gettreedepth(treenode* ptreenode)

return ileftdepth > irightdepth ? (ileftdepth + 1) : (irightdepth + 1);

}// init root tree node

status initroottreenode(sqtree* psqtree)

// insert a treenode in tree

status inserttreenode(sqtree* psqtree, elemtype elem)

} while (ptreenode != null)

return ok;

}// 刪除指定的元素

status deletetreenode(treenode* ptreenode, elemtype elem)

ptreenode = ptreenode->plefttree;

} while (ptreenode->prighttree != null)

return ok;

}// 層序插入結點的實現

status inserttreenodevialayertr**el(sqtree* psqtree, elemtype elem)

else

// 如果當前的結點的右結點是為空的話,同樣也break

if (plinknode->ptreenode->prighttree == null)

else

} // 上面出來了之後那麼說明當前的plinknode指標的左子樹的指標或者右子樹的指標為空

// 那麼此時就可以進行插入操作了

/* pinserttreenode = malloc(sizeof(treenode));

memset(pinserttreenode, 0, sizeof(treenode));

pinserttreenode->nodedata = elem;

if (ileftflag == 1)

plinknode->ptreenode->plefttree = pinserttreenode;

else if (irightflag == 1)

plinknode->ptreenode->prighttree = pinserttreenode;*/

return ok;

}// 層序遍歷/層次遍歷

status layertr**el(sqtree* psqtree)

return ok;

}// 搜尋二叉樹實現

status searchtreenode(treenode* ptreenode)

return ok;

}int main()

測試用例

------1

----2---3

---4-5-6-7

執行結果如下

樹的層序遍歷(靜態佇列實現)

include include typedef struct treetree,tree typedef struct queueque 建立隊 que qcreate 入隊 void enqueue que p,tree s 出隊 tree dequeue que p 判斷空 intisempty...

樹的層序遍歷

層序遍歷的基本思路就是,1.根節點入佇列。2.根節點出隊,同時將根節點左兒子和右兒子入隊 3.結點出隊,同時將該節點的左兒子和右兒子入隊 4.重複3直到隊列為空 void layerprint struct treenode r include include fun.c struct queue ...

佇列實現二叉樹的層序遍歷

首先定義佇列的結構體和方法。佇列使用二維指標儲存指向樹節點的指標。i,j為指向佇列開頭 結尾元素的游標。struct queuebtree typedef struct queuebtree queuebtree queuebtree initqueuebtree void freequeuebtr...