數據結構 · 二叉樹遍歷

一:建立二叉樹結構spa

1 struct tree{
2     char c;
3     tree left;
4     tree right;
5 };

二:基於BFS的遞歸遍歷:code

一、先序遍歷blog

1 void preorder(tree t){
2     if(!t) 
3         return;
4     visit(t);
5     preorder(t->left);
6     preorder(t->right);
7 }

二、中序遍歷遞歸

1 void inorder(tree t){
2     if(!t)
3         return;
4     lastorder(t->left);
5     visit(t);
6     lastorder(t->right);
7 }

三、後序遍歷隊列

1 void lastorder(tree t){
2     if(!t)
3         return;
4     inorder(t->left);
5     inorder(t->right);
6     visit(t);
7 }

 

三:基於BFS的層序遍歷it

  層序遍歷用隊列實現,從根節點開始,首先將根節點入隊,而後執行循環:結點出隊並訪問,左右結點入隊,直到隊列爲空,造成按廣度優先搜索(BFS)的遍歷方式。
       基本過程:
         1) 根節點入隊;
         2) 從隊列中出隊一個結點;
         3) 訪問該結點;
         4) 若是該結點左右子結點非空,依次入隊;
         5) 隊列爲空,遍歷結束。
 1 void  cengorder(tree t){
 2     if(!t)
 3         return;
 4     queue<tree> re;
 5     tree p = T;
 6     re.push(p);
 7     while(!re.empty()){
 8         p = re.front();
 9         visit(p);
10         if(p->left)
11             re.push(p->left);
12         if(p->right)
13             re.push(p->right)
14     }
15 }
相關文章
相關標籤/搜索