一:建立二叉树结构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 }