二叉树的前,中,后序遍历
public static class Node {
public int value;
public Node left;
public Node right;
public Node ( int value) {
this . value = value;
}
}
前序遍历
1.递归方式
private static void preOrderRecur ( Node head) {
if ( null == head) {
return ;
}
System . out. print ( head. value + " " ) ;
preOrderRecur ( head. left) ;
preOrderRecur ( head. right) ;
}
2.非递归方式
private static void preOrderRecur1 ( Node head) {
if ( null == head) {
return ;
}
Stack < Node > stack = new Stack < > ( ) ;
stack. push ( head) ;
while ( ! stack. isEmpty ( ) ) {
Node node = stack. pop ( ) ;
System . out. print ( node. value + " " ) ;
if ( node. right != null ) {
stack. push ( node. right) ;
}
if ( node. left != null ) {
stack. push ( node. left) ;
}
}
}
中序遍历
1.递归方式
private static void inOrderRecur ( Node head) {
if ( null == head) {
return ;
}
inOrderRecur ( head. left) ;
System . out. print ( head. value + " " ) ;
inOrderRecur ( head. right) ;
}
2.非递归方式
private static void inOrderRecur1 ( Node head) {
if ( null == head) {
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. print ( head. value + " " ) ;
head = head. right;
}
}
}
后序遍历
1.递归方式
private static void postOrderRecur ( Node head) {
if ( null == head) {
return ;
}
postOrderRecur ( head. left) ;
postOrderRecur ( head. right) ;
System . out. print ( head. value + " " ) ;
}
2.非递归方式
private static void postOrderRecur1 ( Node head) {
if ( null == head) {
return ;
}
Stack < Node > stack1 = new Stack < > ( ) ;
Stack < Node > stack2 = new Stack < > ( ) ;
stack1. push ( head) ;
while ( ! stack1. isEmpty ( ) ) {
head = stack1. pop ( ) ;
stack2. push ( head) ;
if ( null != head. left) {
stack1. push ( head. left) ;
}
if ( null != head. right) {
stack1. push ( head. right) ;
}
}
while ( ! stack2. isEmpty ( ) ) {
System . out. print ( stack2. pop ( ) . value + " " ) ;
}
}
private static void postOrderRecur2 ( Node head) {
if ( null == head) {
return ;
}
Stack < Node > stack = new Stack < > ( ) ;
stack. push ( head) ;
Node node;
while ( ! stack. isEmpty ( ) ) {
node = stack. peek ( ) ;
if ( node. left != null && head != node. left && head != node. right) {
stack. push ( node. left) ;
} else if ( null != node. right && head != node. right) {
stack. push ( node. right) ;
} else {
System . out. print ( stack. pop ( ) . value + " " ) ;
head = node;
}
}
}