Node结构
public static class Node{
private int value;
private Node left;
private Node right;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
先序递归方式
public static void pre(Node head){
if(head == null){
return ;
}
System.out.println(head.value);
pre(head.left);
pre(head.right);
}
中序递归方式
public static void in(Node head){
if(head == null){
return ;
}
in(head.left);
System.out.println(head.value);
in(head.right);
}
后序递归方式
public static void post(Node head){
if(head == null){
return ;
}
post(head.left);
post(head.right);
System.out.println(head.value);
}
先序无递归方式
public static void pre1(Node head){
if(head == null){
return ;
}
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()){
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 static void in2(Node head){
if(head == null){
return ;
}
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.println(head.value);
head = head.right;
}
}
}
后序无递归方式
public static void post2(Node head){
if(head == null){
return ;
}
Stack<Node> stack = new Stack<>();
Stack<Node> stack1 = new Stack<>();
stack.push(head);
while (!stack.isEmpty()){
stack1.push(stack.pop());
if(head.left != null){
stack.push(head.left);
}
if(head.right != null){
stack.push(head.right);
}
}
while (!stack1.isEmpty()){
System.out.println(stack1.pop().value);
}
}
后序无递归还有一个省空间的方式,自己没理解透,以后再说。。。。。。。