二叉樹 48 二叉樹 二叉樹的高度

2021-10-20 04:02:47 字數 2623 閱讀 5074

目的:使用c++模板設計並逐步完善二叉樹的抽象資料型別(adt)。

內容:(1)請參照鍊錶的adt模板,設計二叉樹並逐步完善的抽象資料型別。(由於該環境目前僅支援單檔案的編譯,故將所有內容都集中在乙個原始檔內。在實際的設計中,推薦將抽象類及對應的派生類分別放在單獨的標頭檔案中。參考教材、課件,以及網盤中的鍊錶adt原型檔案,自行設計二叉樹的adt。)

注意:二叉樹adt的基本操作的演算法設計很多要用到遞迴的程式設計方法。

(2)基本操作9:在二叉樹的二叉鍊錶儲存形式建立的基礎上,使用遞迴的程式設計方法,設計並完成計算二叉樹中以元素值x的結點為根結點的(子)樹的高度的演算法。完成後將其加入到二叉樹的adt基本操作集中。

初始條件:二叉樹t存在,x是t中某個結點。

操作結果:若x是t的結點,則返回以它為根結點的(子)樹的高度(查詢成功)。否則返回0(查詢失敗)。

(1)計算以元素值x為根結點的(子)二叉樹的高度(外殼部分,使用者函式)

//計算以元素值x為根結點的(子)二叉樹的高度(外殼) 

template

int getbinarytreeheight(binarytree&t, elemtype &x);

(2)計算二叉樹的高度(遞迴部分,成員函式)

//計算二叉樹的高度(遞迴) 

template

int binarytree::getbinarytreeheight( binarytreenode*root ) const;

(3)輔助函式:查詢元素值為x的結點的位置(參見基本操作8)

第一行:表示無孩子或指標為空的特殊分隔符

第二行:二叉樹的先序序列(結點元素之間以空格分隔)

第三行:元素值x

第一行:查詢成功:(子)樹的高度

查詢失敗:0(空樹或非樹結點)

#

a b # c d # # e # # f # g # h # #

a

// tree.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始並結束。

//#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std;

vectordepartstring_string(string data)

//————————————————

templatestruct tree_point ;

templateclass binarytree

~binarytree()

void binarytree_fron(vectorlis, elemtype nut)

else if (flag == 1)

s.push(p_parent);

flag = 0;

}else

i++;

} }tree_point* get_root()

void qianxu(tree_point* t)

void zhongxu(tree_point* t)

void houxu(tree_point* t)

int c_t = 0;

void cengxu(tree_point* t)

c_t++;

} }void out_lis()

outlist.clear();

} int cnt = 0, p_cnt = 0;

void t_cnt(tree_point* t)

int cengshu()

int p_cengshu(tree_point* t)

int twocnt()

int p_twocnt(tree_point* t)

int pointcnt()

tree_point* find_father(tree_point* t, elemtype ss)

tree_point* find_self(tree_point* t, elemtype ss) };

int main()

cout << part_in.size() << endl;

cout << nulls << endl;*/

//***********************************===

a.binarytree_fron(part_in, nulls);

/*a.qianxu(a.get_root());

a.out_lis();

a.zhongxu(a.get_root());

a.out_lis();

a.houxu(a.get_root());

a.out_lis();*/

//cout<* ans = a.find_self(a.get_root(), found);

if (ans == null)

cout << 0 << endl;

else

cout << a.p_cengshu(ans) << endl;

return 0;

}

二叉樹 二叉樹

題目描述 如上所示,由正整數1,2,3 組成了一顆特殊二叉樹。我們已知這個二叉樹的最後乙個結點是n。現在的問題是,結點m所在的子樹中一共包括多少個結點。比如,n 12,m 3那麼上圖中的結點13,14,15以及後面的結點都是不存在的,結點m所在子樹中包括的結點有3,6,7,12,因此結點m的所在子樹...

樹 二叉樹 滿二叉樹 完全二叉樹 完滿二叉樹

目錄名稱作用根 樹的頂端結點 孩子當遠離根 root 的時候,直接連線到另外乙個結點的結點被稱之為孩子 child 雙親相應地,另外乙個結點稱為孩子 child 的雙親 parent 兄弟具有同乙個雙親 parent 的孩子 child 之間互稱為兄弟 sibling 祖先結點的祖先 ancesto...

二叉樹,完全二叉樹,滿二叉樹

二叉樹 是n n 0 個結點的有限集合,它或者是空樹 n 0 或者是由乙個根結點及兩顆互不相交的 分別稱為左子樹和右子樹的二叉樹所組成。滿二叉樹 一顆深度為k且有2 k 1個結點的二叉樹稱為滿二叉樹。說明 除葉子結點外的所有結點均有兩個子結點。所有葉子結點必須在同一層上。完全二叉樹 若設二叉樹的深度...