您好,登錄后才能下訂單哦!
本文實(shí)例講述了C++使用遞歸和非遞歸算法實(shí)現(xiàn)的二叉樹葉子節(jié)點(diǎn)個(gè)數(shù)計(jì)算方法。分享給大家供大家參考,具體如下:
/*求二叉樹葉子節(jié)點(diǎn)個(gè)數(shù) -- 采用遞歸和非遞歸方法 經(jīng)調(diào)試可運(yùn)行源碼及分析如下: ***/ #include <stdlib.h> #include <iostream> #include <stack> using std::cout; using std::cin; using std::endl; using std::stack; /*二叉樹結(jié)點(diǎn)定義*/ typedef struct BTreeNode { char elem; struct BTreeNode *pleft; struct BTreeNode *pright; }BTreeNode; /* 求二叉樹葉子節(jié)點(diǎn)數(shù) 葉子節(jié)點(diǎn):即沒有左右子樹的結(jié)點(diǎn) 遞歸方式步驟: 如果給定節(jié)點(diǎn)proot為NULL,則是空樹,葉子節(jié)點(diǎn)為0,返回0; 如果給定節(jié)點(diǎn)proot左右子樹均為NULL,則是葉子節(jié)點(diǎn),且葉子節(jié)點(diǎn)數(shù)為1,返回1; 如果給定節(jié)點(diǎn)proot左右子樹不都為NULL,則不是葉子節(jié)點(diǎn),以proot為根節(jié)點(diǎn)的子樹葉子節(jié)點(diǎn)數(shù)=proot左子樹葉子節(jié)點(diǎn)數(shù)+proot右子樹葉子節(jié)點(diǎn)數(shù)。 /*遞歸實(shí)現(xiàn)求葉子節(jié)點(diǎn)個(gè)數(shù)*/ int get_leaf_number(BTreeNode *proot) { if(proot == NULL) return 0; if(proot->pleft == NULL && proot->pright == NULL) return 1; return (get_leaf_number(proot->pleft) + get_leaf_number(proot->pright)); } /*非遞歸:本例采用先序遍歷計(jì)算 判斷當(dāng)前訪問的節(jié)點(diǎn)是不是葉子節(jié)點(diǎn),然后對(duì)葉子節(jié)點(diǎn)求和即可。 **/ int preorder_get_leaf_number(BTreeNode* proot) { if(proot == NULL) return 0; int num = 0; stack <BTreeNode*> st; while (proot != NULL || !st.empty()) { while (proot != NULL) { cout << "節(jié)點(diǎn):" << proot->elem << endl; st.push(proot); proot = proot->pleft; } if (!st.empty()) { proot = st.top(); st.pop(); if(proot->pleft == NULL && proot->pright == NULL) num++; proot = proot -> pright; } } return num; } /*初始化二叉樹根節(jié)點(diǎn)*/ BTreeNode* btree_init(BTreeNode* &bt) { bt = NULL; return bt; } /*先序創(chuàng)建二叉樹*/ void pre_crt_tree(BTreeNode* &bt) { char ch; cin >> ch; if (ch == '#') { bt = NULL; } else { bt = new BTreeNode; bt->elem = ch; pre_crt_tree(bt->pleft); pre_crt_tree(bt->pright); } } int main() { int tree_leaf_number = 0; BTreeNode *bt; btree_init(bt);//初始化根節(jié)點(diǎn) pre_crt_tree(bt);//創(chuàng)建二叉樹 tree_leaf_number = get_leaf_number(bt);//遞歸 cout << "二叉樹葉子節(jié)點(diǎn)個(gè)數(shù)為:" << tree_leaf_number << endl; cout << "非遞歸先序遍歷過程如下:" << endl; tree_leaf_number = preorder_get_leaf_number(bt);//非遞歸 cout << "二叉樹葉子節(jié)點(diǎn)個(gè)數(shù)為:" << tree_leaf_number << endl; system("pause"); return 0; } /* 運(yùn)行結(jié)果: a b c # # # d e # # f # # ---以上為輸入--- ---以下為輸出--- 二叉樹葉子節(jié)點(diǎn)個(gè)數(shù)為:3 非遞歸遍歷過程如下: 節(jié)點(diǎn):a 節(jié)點(diǎn):b 節(jié)點(diǎn):c 節(jié)點(diǎn):d 節(jié)點(diǎn):e 節(jié)點(diǎn):f 二叉樹葉子節(jié)點(diǎn)個(gè)數(shù)為:3 請(qǐng)按任意鍵繼續(xù). . . 本例創(chuàng)建的二叉樹形狀: a b d c e f */
希望本文所述對(duì)大家C++程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。