package Main;
import java.util.Stack;
public class Test2 {
public static void main(String[] args) {
Tree root=new Tree(0);
root.left=new Tree(1);
root.right=new Tree(2);
root.left.left=new Tree(3);
root.left.right=new Tree(4);
root.right.left=new Tree(5);
root.right.right=new Tree(6);
root.left.left.left=new Tree(7);
root.right.right.right=new Tree(8);
//前序遍历(非递归) 根左右
System.out.println("前序遍历(非递归)");
Stackstack=new Stack<>();
Tree t=root;
stack.push(t);
while(!stack.isEmpty()) {//思路:根据前序遍历(根左右)特点,优先遍历根节点,再而处理左右节点,通过循环就可以实现前序遍历
t=stack.pop();
System.out.print(t.val()+" ");
if(t.right!=null) {
stack.push(t.right);
}
if(t.left!=null) {
stack.push(t.left);
}
}
System.out.println("");
//后序遍历(非递归) 左根右
System.out.println("后序遍历(非递归)");
Stackstack2=new Stack<>();
Stackstack3=new Stack<>();
Tree t2=root;
stack2.push(t2);
while(!stack2.isEmpty()) {//这里先根据Stack先进后出的特性,将二叉树通过后序遍历特点push进stack
t2=stack2.pop();
stack3.push(t2);
if(t2.left!=null) {
stack2.push(t2.left);
}
if(t2.right!=null) {
stack2.push(t2.right);
}
}
while(!stack3.isEmpty()) {//最后将stack出栈,就可以达到后序遍历二叉树
System.out.print(stack3.pop().val()+" ");
}
System.out.println();
//中序遍历(非递归) 左右根
System.out.println("中序遍历(非递归)");
Stackstack4=new Stack<>();
Tree t3=root;
while(t3!=null||!stack4.isEmpty()) {//思路:根据中序遍历特点,优先找左节点
if(t3!=null) {
stack4.push(t3);
t3=t3.left;
}else {
t3=stack4.pop();
System.out.print(t3.val()+" ");
t3=t3.right;
}
}
System.out.println("\n前序遍历(递归)");
pre(root);
System.out.println("\n后序遍历(递归)");
last(root);
System.out.println("\n中序遍历(递归)");
mid(root);
}
//前序遍历(递归)
public static void pre(Tree root) {
if(root!=null) {
System.out.print(root.val()+" ");
pre(root.left);
pre(root.right);
}
}
//中序遍历(递归)
public static void mid(Tree root) {
if(root!=null) {
mid(root.left);
System.out.print(root.val()+" ");
mid(root.right);
}
}
//后序遍历(递归)
public static void last(Tree root) {
if(root!=null) {
last(root.left);
last(root.right);
System.out.print(root.val()+" ");
}
}
}
class Tree{
private int val;
public Tree left;
public Tree right;
public Tree(int val) {
this.val=val;
}
public int val() {
return this.val;
}
}
二叉树形状
遍历输出结果
前序遍历(非递归)
0 1 3 7 4 2 5 6 8
后序遍历(非递归)
7 3 4 1 5 8 6 2 0
中序遍历(非递归)
7 3 1 4 0 5 2 6 8
前序遍历(递归)
0 1 3 7 4 2 5 6 8
后序遍历(递归)
7 3 4 1 5 8 6 2 0
中序遍历(递归)
7 3 1 4 0 5 2 6 8