public class BinaryTree {
public int root;
public BinaryTree leftChild;
public BinaryTree rightChild;
public BinaryTree ( int root) {
this . root = root;
}
@Override
public String toString ( ) {
return "BinaryTree{" +
"root=" + root +
", leftChild=" + leftChild +
", rightChild=" + rightChild +
'}' ;
}
public void insert ( BinaryTree root, int data) {
if ( data>= root. root) {
if ( null== root. rightChild) {
root. rightChild= new BinaryTree ( data) ;
} else {
root. rightChild. insert ( root. rightChild, data) ;
}
} else {
if ( null== root. leftChild) {
root. leftChild= new BinaryTree ( data) ;
} else {
root. leftChild. insert ( root. leftChild, data) ;
}
}
}
public void preQuery ( BinaryTree binaryTree) {
if ( null!= binaryTree) {
System. out. print ( binaryTree. root+ "-" ) ;
binaryTree. preQuery ( binaryTree. leftChild) ;
binaryTree. preQuery ( binaryTree. rightChild) ;
}
}
public void inQuery ( BinaryTree binaryTree) {
if ( null!= binaryTree) {
binaryTree. inQuery ( binaryTree. leftChild) ;
System. out. print ( binaryTree. root+ "-" ) ;
binaryTree. inQuery ( binaryTree. rightChild) ;
}
}
public void lastQuery ( BinaryTree binaryTree) {
if ( null!= binaryTree) {
binaryTree. lastQuery ( binaryTree. leftChild) ;
binaryTree. lastQuery ( binaryTree. rightChild) ;
System. out. print ( binaryTree. root+ "-" ) ;
}
}
public static void main ( String[ ] args) {
BinaryTree binaryTree= new BinaryTree ( 5 ) ;
binaryTree. insert ( binaryTree, 6 ) ;
binaryTree. insert ( binaryTree, 4 ) ;
binaryTree. insert ( binaryTree, 3 ) ;
binaryTree. insert ( binaryTree, 2 ) ;
binaryTree. insert ( binaryTree, 7 ) ;
binaryTree. insert ( binaryTree, 8 ) ;
binaryTree. insert ( binaryTree, 6 ) ;
System. out. println ( "前序:" ) ;
binaryTree. preQuery ( binaryTree) ;
System. out. println ( "\n" ) ;
System. out. println ( "中序:" ) ;
binaryTree. inQuery ( binaryTree) ;
System. out. println ( "\n" ) ;
System. out. println ( "后序:" ) ;
binaryTree. lastQuery ( binaryTree) ;
}
}
结果
前序:
5 - 4 - 3 - 2 - 6 - 7 - 6 - 8 -
中序:
2 - 3 - 4 - 5 - 6 - 6 - 7 - 8 -
后序:
2 - 3 - 4 - 6 - 8 - 7 - 6 - 5 -