实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式
import java.util.Stack;
public class e01PreInPosTraversal {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value=data;
}
}
public static void preOrder(Node head){
if (head==null){
return;
}
System.out.print(head.value+" ");
preOrder(head.left);
preOrder(head.right);
}
public static void inOrder(Node head){
if (head==null){
return;
}
inOrder(head.left);
System.out.print(head.value+" ");
inOrder(head.right);
}
public static void postOrder(Node head){
if (head==null){
return;
}
postOrder(head.left);
postOrder(head.right);
System.out.print(head.value+" ");
}
public static void preOrderNR(Node head){
if (head!=null){
Stack<Node> stack=new Stack<>();
stack.push(head);
Node res=null;
while (!stack.isEmpty()){
res=stack.pop();
System.out.print(res.value+" ");
if (res.right!=null){
stack.push(res.right);
}
if (res.left!=null){
stack.push(res.left);
}
}
}
}
public static void inOrderNR(Node head){
if (head!=null){
Stack<Node> stack=new Stack<>();
Node cur=head;
while (!stack.isEmpty()||cur!=null){
if (cur!=null){
stack.push(cur);
cur=cur.left;
}else{
cur=stack.pop();
System.out.print(cur.value+" ");
cur=cur.right;
}
}
}
}
public static void postOrderNR(Node head){
if (head!=null){
Stack<Node> s1=new Stack<>();
Stack<Node> s2=new Stack<>();
s1.push(head);
Node res=null;
while (!s1.isEmpty()){
res=s1.pop();
s2.push(res);
if (res.left!=null){
s1.push(res.left);
}
if (res.right!=null){
s1.push(res.right);
}
}
while (!s2.isEmpty()){
System.out.print(s2.pop().value+" ");
}
}
}
public static void main(String[] args) {
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(8);
head.left.left = new Node(2);
head.left.right = new Node(4);
head.left.left.left = new Node(1);
head.right.left = new Node(7);
head.right.left.left = new Node(6);
head.right.right = new Node(10);
head.right.right.left = new Node(9);
head.right.right.right = new Node(11);
System.out.println("==============recursive==============");
System.out.print("pre-order: ");
preOrder(head);
System.out.println();
System.out.print("in-order: ");
inOrder(head);
System.out.println();
System.out.print("post-order: ");
postOrder(head);
System.out.println();
System.out.println("============unrecursive=============");
System.out.print("pre-order: ");
preOrderNR(head);
System.out.println();
System.out.print("in-order: ");
inOrderNR(head);
System.out.println();
System.out.print("post-order: ");
postOrderNR(head);
System.out.println();
}
}