1. 程式人生 > 實用技巧 >二叉樹的操作及遍歷

二叉樹的操作及遍歷

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int Max_N;
 4 
 5 //1.樹的節點定義 
 6 struct node{
 7     char val;//結點值 
 8     int lch, rch;//左右兒子(指向結構體陣列下標) 
 9 }; 
10 
11 //2.定義樹,用結構體陣列儲存 
12 node tree[Max_N];
13 int id;//陣列下標標記 
14 
15 //3.構建樹
16 void build(int root)
17 {
18     char c;
19     cin>>c;
20 tree[root].val=c; 21 22 tree[root].lch=++id; 23 build(tree[root].lch);//或者build(id); 遞迴進入左子樹 24 tree[root].rch=++id; 25 build(tree[root].rch);//或者build(id); 遞迴進入右子樹 26 } 27 28 //4.遍歷 29 void xxbl(int root)//4.1 先序遍歷 30 { 31 cout<<tree[root].val;//對根進行操作 32 33 if
(tree[root].lch)//左子樹非空時,遞迴進入左子樹 34 xxbl(tree[root].lch); 35 36 if(tree[root].rch)//右子樹非空時,遞迴進入右子樹 37 xxbl(tree[root].rch); 38 } 39 void zxbl(int root)//4.2 中序遍歷 40 { 41 if(tree[root].lch)//左子樹非空時,遞迴進入左子樹 42 zxbl(tree[root].lch); 43 44 cout<<tree[root].val;//
對根進行操作 45 46 if(tree[root].rch)//右子樹非空時,遞迴進入右子樹 47 zxbl(tree[root].rch); 48 } 49 void hxbl(int root)//4.3 後序遍歷 50 { 51 if(tree[root].lch)//左子樹非空時,遞迴進入左子樹 52 hxbl(tree[root].lch); 53 54 if(tree[root].rch)//右子樹非空時,遞迴進入右子樹 55 hxbl(tree[root].rch); 56 57 cout<<tree[root].val;//對根進行操作 58 } 59 int main() 60 { 61 build(1);//樹根結點從1開始 62 xxbl(1); 63 zxbl(1); 64 hxbl(1); 65 66 return 0; 67 }