二叉树前,中,后序遍历(递归实现):
public class Tree {
class TreeNode {
int val= 0 ;
TreeNode left= null;
TreeNode right= null;
public TreeNode ( int val) {
this . val= val;
}
}
public void prevOrder ( TreeNode root) {
if ( root== null) return ;
System. out. print ( root. val+ " " ) ;
prevOrder ( root. left) ;
prevOrder ( root. right) ;
}
public void inOrder ( TreeNode root) {
if ( root== null) return ;
inOrder ( root. left) ;
System. out. print ( root. val+ " " ) ;
inOrder ( root. right) ;
}
public void postOrder ( TreeNode root) {
if ( root== null) return ;
postOrder ( root. left) ;
postOrder ( root. right) ;
System. out. print ( root. val+ " " ) ;
}
}
前,中,后序遍历(非递归实现)+层次遍历:
public class Tree {
class TreeNode {
int val= 0 ;
TreeNode left= null;
TreeNode right= null;
public TreeNode ( int val) {
this . val= val;
}
}
public List< Integer> preOrder ( TreeNode root) {
List< Integer> list= new LinkedList < > ( ) ;
Stack< TreeNode> stack= new Stack < > ( ) ;
if ( root== null) return list;
stack. push ( root) ;
while ( ! stack. isEmpty ( ) ) {
TreeNode node= stack. pop ( ) ;
list. add ( node. val) ;
if ( node. right!= null) {
stack. push ( node. right) ;
}
if ( node. left!= null) {
stack. push ( node. left) ;
}
}
return list;
}
public List< Integer> inOrder ( TreeNode root) {
List< Integer> list= new LinkedList < > ( ) ;
Stack< TreeNode> stack= new Stack < > ( ) ;
TreeNode cur= root;
while ( cur!= null || ! stack. isEmpty ( ) ) {
while ( cur!= null) {
stack. push ( cur) ;
cur= cur. left;
}
cur= stack. pop ( ) ;
list. add ( cur. val) ;
cur= cur. right;
}
return list;
}
public List< Integer> postOrder ( TreeNode root) {
LinkedList< Integer> list= new LinkedList < > ( ) ;
LinkedList< TreeNode> stack= new LinkedList < > ( ) ;
if ( root== null) return list;
stack. push ( root) ;
while ( ! stack. isEmpty ( ) ) {
TreeNode node= stack. pop ( ) ;
list. addFirst ( node. val) ;
if ( root. left!= null) {
stack. add ( root. left) ;
}
if ( root. right!= null) {
stack. add ( root. right) ;
}
}
return list;
}
public LinkedList< LinkedList< Integer> > print ( TreeNode root) {
LinkedList< LinkedList< Integer> > list= new Linkedlist < > ( ) ;
LinkedList< TreeNode> queue= new LinkedList < > ( ) ;
if ( root== null) return list;
queue. add ( root) ;
while ( queue. size ( ) != 0 ) {
int count= queue. size ( ) ;
LinkedList< Integer> list1= new LinkedList < > ( ) ;
while ( count> 0 ) {
TreeNode node= queue. remove ( 0 ) ;
list1. add ( node. val) ;
if ( root. left!= null) {
queue. add ( root. left) ;
}
if ( root. right!= null) {
queue. add ( root. right) ;
}
count-- ;
}
list. add ( list1) ;
}
return list;
}
}