package com.hzins.suanfa;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* 二叉树的遍历
* 其实深度遍历就是前序、中序和后序
* @author Administrator
*
*/
public class TreeTraverse {
public static void main(String[] args) {
Node node0 = new Node(0);
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
node0.left = node1;
node0.right = node2;
node1.left = node3;
node1.right = node4;
node2.left = node5;
node2.right = node6;
}
/**
* 递归先序遍历
* @param head
*/
public static void preOrderRecur(Node head){
if(head == null){
return ;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
/**
* 递归中序遍历
* @param head
*/
public static void inOrderRecur(Node head){
if(head == null){
return;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
/**
* 递归后序遍历
* @param head
*/
public static void posOrderRecur(Node head){
if(head == null){
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
/**
* 非递归先序遍历
* 将head放入stack中
* pop出来,打印出node值,如果此时node有right,则将right压入stack中,
* 如果此时有left,则将left压入栈中
* @param head
*/
public static void pre(Node head){
if(head == null){
return;
}
Stack<Node> stack = new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()){
Node temp = stack.pop();
System.out.println(temp + " ");
if(temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
}
/**
* 非递归实现二叉树的中序遍历
* 将head压入栈中,head的左节点赋值为cur,不断地压入cur,直到发现cur为空,此时stack中弹出一个节点,记为node
* 打印node值,并将cur赋值为node.right
* 当stack为空并且cur为空时,遍历停止
* @param head
*/
public static void in(Node head){
if(head != null){
Stack<Node> stack = new Stack<Node>();
while(!stack.isEmpty() || head != null){
if(head != null){
stack.push(head);
head = head.left;
}
else{
head = stack.pop();
System.out.println(head.value);
head = head.right;
}
}
}
}
/**
* 非递归实现二叉树的后续遍历
* 申请两个栈,记为s1,s2
* 将head节点放入s1中,将s1pop出来放入s2中,将pop出的左右孩子放入s1中,直到s1为空,将s2中的元素输出
* @param haed
*/
public static void pos(Node head){
if(head != null){
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while(!s1.isEmpty()){
Node temp = s1.pop();
if(temp.left != null){
s2.push(temp.left);
}
if(temp.right != null){
s2.push(temp.right);
}
}
while(!s2.isEmpty()){
System.out.print(s2.pop() + " ");
}
}
}
/**
* 层级遍历
*/
public static void ceng(Node head){
if(head != null){
Queue<Node> queue = new LinkedList<Node>();
queue.offer(head);
while(!queue.isEmpty()){
Node temp = queue.poll();
System.out.print(temp + " ");
if(temp.left != null){
queue.offer(temp.left);
}
if(temp.right != null){
queue.offer(temp.right);
}
}
}
}
}