package Demo8;
public class BinaryTreeDemo {
public static void main ( String[ ] args) {
BinaryTree b = new BinaryTree ( ) ;
HeroNode root = new HeroNode ( 1 , "张三" ) ;
HeroNode h2 = new HeroNode ( 2 , "李四" ) ;
HeroNode h3 = new HeroNode ( 3 , "王五" ) ;
HeroNode h4 = new HeroNode ( 4 , "七八" ) ;
HeroNode h5 = new HeroNode ( 5 , "五六" ) ;
root. setLeft ( h2) ;
root. setRight ( h3) ;
h2. setLeft ( h4) ;
h4. setLeft ( h5) ;
b. setRoot ( root) ;
System. out. println ( "前序遍历!" ) ;
b. preOrder ( ) ;
System. out. println ( "中序遍历!" ) ;
b. infixOder ( ) ;
System. out. println ( "后序遍历!" ) ;
b. postOrder ( ) ;
}
}
package Demo8;
public class BinaryTree {
private HeroNode root;
public void BinaryTree ( HeroNode root) {
this . root = root;
}
public HeroNode getRoot ( ) {
return root;
}
public void setRoot ( HeroNode root) {
this . root = root;
}
public void preOrder ( ) {
if ( this . root!= null) {
this . root. preorder ( ) ;
} else {
System. out. println ( "当前二叉树为空!" ) ;
}
}
public void infixOder ( ) {
if ( this . root!= null) {
this . root. infixorder ( ) ;
} else {
System. out. println ( "当前二叉树为空!" ) ;
}
}
public void postOrder ( ) {
if ( this . root!= null) {
this . root. postoder ( ) ;
} else {
System. out. println ( "当前二叉树为空!" ) ;
}
}
}
package Demo8;
public class HeroNode {
private int no;
private String name;
private HeroNode left;
private HeroNode right;
public HeroNode ( ) { }
public HeroNode ( int no, String name) {
this . no = no;
this . name = name;
}
public int getNo ( ) {
return no;
}
public void setNo ( int no) {
this . no = no;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public HeroNode getLeft ( ) {
return left;
}
public void setLeft ( HeroNode left) {
this . left = left;
}
public HeroNode getRight ( ) {
return right;
}
public void setRight ( HeroNode right) {
this . right = right;
}
@Override
public String toString ( ) {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
'}' ;
}
public void preorder ( ) {
System. out. println ( this ) ;
if ( this . left!= null) {
this . left. preorder ( ) ;
}
if ( this . right!= null) {
this . right. preorder ( ) ;
}
}
public void infixorder ( ) {
if ( this . left!= null) {
this . left. infixorder ( ) ;
}
System. out. println ( this ) ;
if ( this . right!= null) {
this . right. infixorder ( ) ;
}
}
public void postoder ( ) {
if ( this . left!= null) {
this . left. postoder ( ) ;
}
if ( this . right!= null) {
this . right. postoder ( ) ;
}
System. out. println ( this ) ;
}
}