一:建立二叉樹結構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
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 }