二叉樹的一系列操作

2021-10-07 09:36:24 字數 3625 閱讀 1993

btree.h

先定義樹的節點:

struct treenode

};

struct btree

;

btree.cpp
void btree::

buildtree

(vector<

int>

&a)//構建二叉搜尋樹

root =

newtreenode

(a[0])

;for

(int i =

1; i < a.

size()

; i++

) node = node-

>left;

}else

node = node-

>right;}}

}}

void btree::

layerorder

(treenode *root)

//層次遍歷(換行)

treenode *last = root;

treenode *nlast =

null

; queue>que;

que.

push

(root)

; cout << endl;

while

(!que.

empty()

)if(node-

>right)

if(node == last)

}}

void btree::

preorder

(treenode *root)

//前序遍歷遞迴實現(根左右)

cout << root-

>val <<

" ";

preorder

(root-

>left)

;preorder

(root-

>right);}

void btree::

inorder

(treenode *root)

//中序遍歷,遞迴實現(左根右)

inorder

(root-

>left)

; cout << root-

>val <<

" ";

inorder

(root-

>right);}

void btree::

postorder

(treenode *root)

//後序遍歷遞迴實現(左右根)

postorder

(root-

>left)

;postorder

(root-

>right)

; cout << root-

>val <<

" ";

}

void btree::

preorderfor

(treenode *root)

//前序遍歷,非遞迴實現

stack>stk;

stk.

push

(root)

; cout <<

"前序遍歷:"

;while

(!stk.

empty()

)if(node-

>left)

} cout<< endl;

}void btree::

inorderfor

(treenode *root)

//中序遍歷,非遞迴實現

cout <<

"中序遍歷:"

; stack>stk;

treenode *cur = root;

while

(!stk.

empty()

|| cur)

treenode *node = stk.

top();

stk.

pop();

cout <>val<<

" ";

cur = node-

>right;}}

void btree::

postorderfor

(treenode *root)

//後序遍歷,非遞迴實現

cout << endl;

cout <<

"後序遍歷:"

; stack>s1;

stack>s2;

s1.push

(root)

;while

(!s1.

empty()

)while

(!s2.

empty()

)}

int  btree::

heightoftree

(treenode *root)

//二叉樹的高度(後序遍歷思想)

int lheight =

heightoftree

(root-

>left)

;int rheight =

heightoftree

(root-

>right)

;int max = lheight > rheight ? lheight : rheight;

return max +1;

}

treenode *btree::

getroot()

void btree::

destroytree

(treenode *root)

//銷毀二叉樹(後序遍歷思想)

destroytree

(root-

>left)

;destroytree

(root-

>right)

;delete root;

root =

null

;}

main.cpp
int

main()

; btree b;

b.buildtree

(a);

//建樹

b.preorderfor

(b.getroot()

);//非遞迴前序

遞迴前序

b.inorderfor

(b.getroot()

);//非遞迴中序

遞迴中序

b.postorderfor

(b.getroot()

);//非遞迴後序

遞迴後序

b.layerorder

(b.getroot()

);//層次遍歷

cout << b.

heightoftree

(b.getroot()

);//樹的高度

b.destroytree

(b.getroot()

);//銷毀樹

return0;

}

二叉樹的一系列操作

遍歷建立二叉樹 先序遍歷的 如下 int k,len,sum,x,y,z void creatbitree bitree t,char ch if ch k 0 else 中序遍歷和後序遍歷只是與先序遍歷遞迴的語句交換 二叉樹的層次遍歷 運用佇列先進先出的特性 過程 1入隊,2入隊,3入隊,1出隊,...

關於mysql 一系列操作

這是在linux 的mysql的資料庫操作,備份資料庫 mysqldump u root p cxn usr local backupcxn.sql 引數說明 cxn 代表著我要備份的資料庫名稱,usr local backupcxn.sql代表著備份到usr local下,輩分的名稱叫做backu...

樹狀陣列的一系列操作

1 樹狀陣列求逆序對 include include include using namespace std const int maxn 100010 int n,a maxn b maxn c maxn s maxn int lowbit int x void add int x int get...