一、递归方式
//先序遍历
public static void preOrderRecur(Node root) {
if (root == null) {
return;
}
System.out.print(root.value+ " ");
preOrderRecur(root.left);
preOrderRecur(root.right);
}
//中序遍历
public static void inOrderRecur(Node root) {
if (root == null) {
return;
}
inOrderRecur(root.left);
System.out.print(root.value+ " ");
inOrderRecur(root.right);
}
//后序遍历
public static void posOrderRecur(Node root) {
if (root == null) {
return;
}
posOrderRecur(root.left);
posOrderRecur(root.right);
System.out.print(root.value+ " ");
}
二、非递归方式
//先序遍历
public static void preOrderUnRecur(Node root) {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
while ((root !=null) || (!stack.isEmpty())) {
while (root != null) {
stack.push(root);
System.out.print(root.value + " ");
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop();
root = root.right;
}
}
}
//中序遍历
public static void inOrderUnRecur(Node root) {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
while ((root !=null) || (!stack.isEmpty())) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop();
System.out.print(root.value + " ");
root = root.right;
}
}
}
//后序遍历
public static void posOrderUnRecur(Node root) {
if (root != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(root);
while (!s1.isEmpty()) {
root = s1.pop();
s2.push(root);
if (root.left != null) {
s1.push(root.left);
}
if (root.right != null) {
s1.push(root.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
}
}