二叉树的遍历
package zuochengyun;
import java.util.Stack;
public class PrintErChashu {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int i) {
this.value=i;
}
}
public static void preOrder(Node head) {
if(head==null)
return;
System.out.print(head.value);
preOrder(head.left);
preOrder(head.right);
}
public static void innerOrder(Node head) {
if(head==null)
return;
innerOrder(head.left);
System.out.print(head.value+",");
innerOrder(head.right);
}
public static void lateOrder(Node head) {
if(head==null)
return;
lateOrder(head.left);
lateOrder(head.right);
System.out.print(head.value+"-");
}
public static void preOrder1(Node head) {
if(head!=null) {
Stack<Node> stack=new Stack<>();
stack.push(head);
while(!stack.isEmpty()) {
head=stack.pop();
System.out.print(head.value+"");
if(head.right!=null) {
stack.push(head.right);
}
if(head.left!=null) {
stack.push(head.left);
}
}
}
}
public static void innerOrder1(Node head) {
if(head!=null) {
Stack<Node> stack=new Stack<>();
while(!stack.isEmpty()||head!=null) {
if(head!=null) {
stack.push(head);
head=head.left;
}else {
head=stack.pop();
System.out.print(head.value+",");
head=head.right;
}
}
}
}
public static void lateOrder1(Node head) {
if(head!=null) {
Stack<Node> stack = new Stack<>();
Stack<Node> stack2 = new Stack<>();
stack.push(head);
while(!stack.isEmpty()) {
head=stack.pop();
stack2.push(head);
if(head.left!=null) {
stack.push(head.left);
}
if(head.right!=null){
stack.push(head.right);
}
}
while(!stack2.isEmpty()) {
System.out.print(stack2.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("递归,先序");
preOrder(head);
System.out.println("非递归,先序");
preOrder1(head);
System.out.println();
System.out.println("-------------------------");
}
}