结构:
public class BiTree {
public BiTree lchild;
public BiTree rchild;
public int element;
public boolean isVisited = false;
public boolean isPolled = false;
public BiTree(int element){
this.element = element;
}
public void visit(){
isVisited = true;
System.out.print(element);
}
}
1.递归先序遍历
public void preOrder(BiTree b) {
if (b != null) {
b.visit();
preOrder(b.lchild);
preOrder(b.rchild);
}
}
2.递归中序遍历
public void inOrder(BiTree b) {
if (b != null) {
inOrder(b.lchild);
b.visit();
inOrder(b.rchild);
}
}
3.递归后序遍历
public void postOrder(BiTree b) {
if (b != null) {
postOrder(b.lchild);
postOrder(b.rchild);
b.visit();
}
}
4.非递归先序遍历
public void preOrder2(BiTree b) {
LinkedList<BiTree> stack = new LinkedList<>();
BiTree p = b;
while (p != null) {
if (!p.isVisited) {
p.visit();
if (p.lchild != null) {
stack.push(p);
p = p.lchild;
continue;
} else {
if (p.rchild != null) {
p = p.rchild;
continue;
}
}
} else {
if (p.rchild != null) {
p = p.rchild;
continue;
}
}
p = stack.pop();
}
}
5.非递归中序遍历
public void inOrder2(BiTree b) {
LinkedList<BiTree> stack = new LinkedList<>();
BiTree p = b;
while (p != null) {
stack.push(p);
if (p.lchild != null) {
p = p.lchild;
continue;
}
p.visit();
while (p.rchild == null) {
p = stack.pop();
p.visit();
}
p = p.rchild;
}
}
6.非递归后序遍历
public void postOrder2(BiTree b) {
LinkedList<BiTree> stack = new LinkedList<>();
BiTree p = b;
while (true) {
if (p.lchild != null) {
stack.push(p);
p = p.lchild;
continue;
}
if (p.rchild != null) {
p.isPolled = true;
stack.push(p);
p = p.rchild;
continue;
}
p.visit();
while (!stack.isEmpty()) {
p = stack.pop();
if (p.isPolled) {
p.visit();
} else {
if (p.rchild != null) {
p.isPolled = true;
stack.push(p);
p = p.rchild;
break;
}
p.visit();
}
}
if (stack.isEmpty()) break;
}
}
7.层次遍历
public void levelOrder(BiTree b) {
LinkedList<BiTree> queue = new LinkedList<>();
BiTree p = b;
queue.add(p);
while (!queue.isEmpty()) {
p = queue.poll();
p.visit();
if (p.lchild != null) queue.add(p.lchild);
if (p.rchild != null) queue.add(p.rchild);
}
}