public static List< Integer> preOrder ( TreeNode root) {
List< Integer> list = new ArrayList < > ( ) ;
if ( root == null) {
return list;
}
Stack< TreeNode> stack = new Stack < > ( ) ;
stack. push ( root) ;
while ( ! stack. isEmpty ( ) ) {
TreeNode get = stack. pop ( ) ;
list. add ( get. value) ;
if ( get. right != null) {
stack. push ( get. right) ;
}
if ( get. left != null) {
stack. push ( get. left) ;
}
}
return list;
}
public static List< Integer> infixOrder ( TreeNode root) {
List< Integer> list = new ArrayList < > ( ) ;
if ( root == null) {
return list;
}
TreeNode p = root;
Stack< TreeNode> stack = new Stack < > ( ) ;
while ( p != null || ! stack. isEmpty ( ) ) {
while ( p != null) {
stack. push ( p) ;
p = p. left;
}
p = stack. pop ( ) ;
list. add ( p. value) ;
p = p. right;
}
return list;
}
public List< Integer> postOrderByPreOrder ( TreeNode root) {
List< Integer> list = new ArrayList < > ( ) ;
if ( root == null) {
return list;
}
Stack< TreeNode> stack = new Stack < > ( ) ;
stack. push ( root) ;
TreeNode p = null;
while ( ! stack. isEmpty ( ) ) {
p = stack. pop ( ) ;
list. add ( p. value) ;
if ( p. left != null) {
stack. push ( p. left) ;
}
if ( p. right != null) {
stack. push ( p. right) ;
}
}
return list;
}
public List< Integer> postOrder ( TreeNode root) {
if ( root == null) {
return list;
}
TreeNode p = root;
TreeNode last = null;
Stack< TreeNode> s = new Stack < > ( ) ;
while ( p != null || ! s. isEmpty ( ) ) {
while ( p != null) {
s. push ( p) ;
p = p. left;
}
p = s. peek ( ) ;
if ( p. right == null || ( last != null && last == p. right) ) {
s. pop ( ) ;
list. add ( p. value) ;
last = p;
p = null;
} else {
p = p. right;
last = null;
}
}
return list;
}