package com.example.demo.test;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Order {
static class Tree {
int value;
Tree left;
Tree right;
public Tree(int value, Tree t1, Tree t2) {
this.value = value;
this.left = t1;
this.right = t2;
}
}
public static Tree init() {
Tree J = new Tree(8, null, null);
Tree H = new Tree(4, null, null);
Tree G = new Tree(2, null, null);
Tree F = new Tree(7, null, J);
Tree E = new Tree(5, H, null);
Tree D = new Tree(1, null, G);
Tree C = new Tree(9, F, null);
Tree B = new Tree(3, D, E);
Tree A = new Tree(6, B, C);
return A; // 返回根节点
}
// 前序遍历
public static void preOrder(Tree tree) {
if (tree == null) {
return;
}
Stack<Tree> stack = new Stack();
Tree node = tree;
while (null != node || !stack.isEmpty()) {
if (null != node) {
System.out.print(node.value + " ");
stack.push(node);
node = node.left;
} else {
node = stack.pop().right;
}
}
}
// 中序遍历
public static void inOrder(Tree tree) {
if (tree == null) {
return;
}
Stack<Tree> stack = new Stack();
Tree node = tree;
while (null != node || !stack.isEmpty()) {
if (null != node) {
stack.push(node);
node = node.left;
} else {
node = stack.pop();
System.out.print(node.value + " ");
node = node.right;
}
}
}
// 后序遍历
public static void lastOrder(Tree tree) {
if (tree == null) {
return;
}
Stack<Tree> stack = new Stack<Tree>();
Stack<Tree> outStack = new Stack<Tree>();
Tree node = tree;
while (null != node || !stack.isEmpty()) {
if (null != node) {
outStack.push(node);
stack.push(node);
node = node.right;
} else {
node = stack.pop();
node = node.left;
}
}
while (!outStack.isEmpty()) {
System.out.print(outStack.pop().value + " ");
}
}
// 深度遍历
public static void deepOrder(Tree tree) {
if (tree == null) {
return;
}
Queue<Tree> queue = new LinkedList<Tree>();
queue.add(tree);
while (!queue.isEmpty()) {
Tree node = queue.poll();
System.out.print(node.value + " ");
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
// 递归方式(前序)
public static void order(Tree tree) {
if (tree != null) {
System.out.print(tree.value + " ");
order(tree.left);
order(tree.right);
}
}
public static void main(String[] args) {
preOrder(Order.init());
order(Order.init());
}
}