-
用递归的方式可以很方便的打印二叉树,因为在递归的调用中每个节点都会经过三次,根据到达节点的先后顺序我们就可以进行打印。
-
用非递归的方式打印。
先序遍历的时候,我们用一个栈来存储节点。如果一个节点存在右孩子我们就将右孩子给加进去,然后如果存在左孩子,就将左孩子给加进去。这样可以保证在弹出的时候是先弹出左孩子的,然后才是右孩子。
后序遍历与先序遍历是相似的,需要将先序遍历的顺序给换过来,先加左孩子在加右孩子,然后用一个额外的栈去存储。
中序遍历:也是用一个栈来存储节点。如果一个节点不为空就将这个节点给加进去,然后等于左孩子;否则的话就弹出一个节点打印,然后指向右孩子。
package Code04;
import java.util.Stack;
public class Code01_PreInPosTraversal {
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);
preOrder(head);
System.out.println();
preOrder1(head);
System.out.println();
inOrder(head);
System.out.println();
inOrder1(head);
System.out.println();
posOrder(head);
System.out.println();
posOrder1(head);
}
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int val){
this.value = val;
}
}
//用递归的方式来前序遍历
public static void preOrder(Node head){
if(head == null)
return ;
System.out.print(head.value+" ");
preOrder(head.left);
preOrder(head.right);
}
//非递归的方式进行前序遍历
public static void preOrder1(Node head){
Stack<Node> stack = new Stack<>();
stack.add(head);
Node node = null;
while(!stack.isEmpty()){
node = stack.pop();
if(node.right != null)
stack.add(node.right);
if(node.left != null)
stack.add(node.left);
System.out.print(node.value+" ");
}
}
//递归的方式进行中序遍历
public static void inOrder(Node head){
if(head == null) return ;
inOrder(head.left);
System.out.print(head.value+" ");
inOrder(head.right);
}
//非递归的方式进行中序遍历
public static void inOrder1(Node head){
if(head == null) return ;
Stack<Node> stack = new Stack<>();
while(! stack.isEmpty() || head != null){
if(head != null){
stack.add(head);
head = head.left;
}else{
head = stack.pop();
System.out.print(head.value+" ");
head = head.right;
}
}
}
//递归的方式进行后序遍历
public static void posOrder(Node head){
if(head == null) return ;
posOrder(head.left);
posOrder(head.right);
System.out.print(head.value+" ");
}
//非递归的方式进行后序遍历
public static void posOrder1(Node head){
if(head == null) return ;
Stack<Node> stack1 = new Stack<>();
Stack<Node> stack2 = new Stack<>();
stack1.add(head);
while(! stack1.isEmpty()){
head = stack1.pop();
stack2.push(head);
if(head.left != null){
stack1.push(head.left);
}
if(head.right != null){
stack1.push(head.right);
}
}
while(! stack2.isEmpty()){
System.out.print(stack2.pop().value+" ");
}
}
}