-
前序:根左右(二叉树的深度优先遍历)
-
中序:左根右
-
后序:左右根
-
层次遍历:就是从根节点开始,一层一层,从上到下,每层从左到右,依次写值就可以了
// 创建二叉树
#include<iostream>
#include<stack>
using namespace std;
class Tree{
public:
char c;
Tree * leftTree;
Tree * rightTree;
};
Tree* createTree(int count){
Tree * t = new Tree();
t->c = count;
t->leftTree = NULL;
t->rightTree = NULL;
return t;
}
void insertTree(Tree* parent,Tree * left,Tree * right){
parent->leftTree = left;
parent->rightTree = right;
}
int main(){
Tree * a = createTree('a');Tree * b = createTree('b');Tree * c = createTree('c');
Tree * d = createTree('d');Tree * e = createTree('e');Tree * f = createTree('f');
Tree * g = createTree('g');
insertTree(a,b,c);insertTree(b,d,NULL);insertTree(c,e,f);insertTree(d,NULL,g);
// 树的结构
a
/ \
b c
/ / \
d e f
\
g
// 先序: abdgcef
// 中序: dgbaecf
// 后序: gdbefca
return 0;
}
递归遍历
先序遍历
void firstPrint(Tree* root){
if(!root) return;
cout<<root->c<<"->";
firstPrint(root->leftTree);
firstPrint(root->rightTree);
}
中序遍历
void midPrint(Tree* root){
if(!root) return;
midPrint(root->leftTree);
cout<<root->c<<"->";
midPrint(root->rightTree);
}
后序遍历
void lastPrint(Tree* root){
if(!root) return;
lastPrint(root->leftTree);
lastPrint(root->rightTree);
cout<<root->c<<"->";
}
非递归遍历
先序遍历
思路:通过栈,先走到左边最深,把经过的节点依次入栈,不能入栈的时候判断栈是否为空,不为空则出栈,root指向出栈元素的右节点,再次判断左是否有元素,栈为空则退出循环
void preByStack(Tree * root){
if(!root) return;
stack<Tree*> s;
while(root||!s.empty()){
if(root){
s.push(root);
cout<<root->c<<"->";
root = root->leftTree;
}else{
root = s.top();
s.pop();
root = root->rightTree;
}
}
}
思路2:先把根节点入栈,再循环,如何栈不为空,弹出一个节点输出,如果该节点有右子树,则入栈,在判断是否有左子树,有再入栈
void preByStack(Tree * root){
if(!root) return;
stack<Tree*> s;
s.push(root);
while(!s.empty()){
Tree* t = s.top();
s.pop();
cout<<root->c<<"->";
if(t->rightTree) s.push(t->rightTree);
if(t->leftTree) s.push(t->leftTree);
}
}
中序遍历
思路:通过栈,把左边的依次入栈,弹出的时候,对弹出节点的右树进行左边的依次入栈的操作
void midByStack(Tree * root){
if(!root) return;
stack<Tree*> s;
while(root||!s.empty()){
if(root){
s.push(root);
root = root->leftTree;
}else{
root = s.top();
s.pop();
cout<<root->c<<"->";
root = root->rightTree;
}
}
}
后序遍历
思路:通过两个栈,先序遍历进行根右左,存入栈里,倒叙输出出来
void lastByStack(Tree * root){
if(!root) return;
stack<Tree*> res,s;
s.push(root);
while(!s.empty()) {
Tree* t = s.top();
s.pop();
res.push(t);
if(t->leftTree) s.push(t->leftTree);
// 右节点后进入先出来
if(t->rightTree) s.push(t->rightTree);
}
// 把根右左倒叙遍历出来
while(!res.empty()){
cout<<res.top()->c<<"->";
res.pop();
}
}
层次遍历
思路:使用一个队列,先把根节点入队列,当对列不为空时,出一个节点,然后判断左右是否为空,不为空把左右入队列
void ciPrint(Tree* root){
if(!root) return;
queue<Tree*> d;
d.push(root);
while(!d.empty()){
Tree *t = d.front();
d.pop();
cout<<t->c<<"->";
if(t->leftTree) d.push(t->leftTree);
if(t->rightTree) d.push(t->rightTree);
}
}