1、递归思路
public class OrderRecur {
public static void main(String args){
int[] array = {12,23,34,54,6,77,6,54,56,6,7,87,15,15,15};
//数组转Node
Node head = array2Node(array);
}
//前序
public void preOrderRecur(Node head){
if(head == null){
return;
}
System.out.println(head.value);
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//中序
public void midOrderRecur(Node head){
if(head == null){
return;
}
midOrderRecur(head.left);
System.out.println(head.value);
midOrderRecur(head.right);
}
//后序
public void posOrderRecur(Node head){
if(head == null){
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.println(head.value);
}
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value = data;
}
}
//数组转二叉树
public static Node array2Node(int[] array){
int lenth = array.length;
Node head = new Node(array[0]);
Node cur = head;
int i = 0;
while(i < lenth){
cur.value = array[i];
i = i+1;
if(i >= lenth){
break;
}
cur.left.value = array[i];
i = i+1;
if(i >= lenth){
break;
}
cur.right.value = array[i];
}
return head;
}
}
2、非递归思路(任何递归实现方法都可以用非递归方式实现)
前序:
//非递归方式的前序排列
public void preOrderWithoutRecur(Node head){
if(head == null){
return;
}
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while(stack != null){
head = stack.pop();
System.out.println(head.value);
if(head.right != null){
stack.push(head.right);
}
if(head.left != null){
stack.push(head.left);
}
}
}
中序:
//用非递归方式完成中序排列
public void midOrderWithoutRecur(Node head){
if(head == null){
return;
}
Stack<Node> stack = new Stack<>();
while(stack != null || head !=null){
if(head != null){
stack.push(head);
head = head.left;
}else{
head = stack.pop();
System.out.println(head.value);
head = head.right;
}
}
}
后序(略,有时间再补)