1 二叉树结构图示
要创建如下图所示的二叉树。
2 代码编写
2.1 树节点定义与前中后遍历算法实现
class HeroNode{
private int no;
private String name;
private HeroNode lchild;//默认为null
private HeroNode rchild;//默认为null
/*getter*/
public int getNo() {
return no;
}
public String getName() {
return name;
}
public HeroNode getLchild() {
return lchild;
}
public HeroNode getRchild() {
return rchild;
}
/*setter*/
public void setNo(int no) {
this.no = no;
}
public void setName(String name) {
this.name = name;
}
public void setLchild(HeroNode lchild) {
this.lchild = lchild;
}
public void setRchild(HeroNode rchild) {
this.rchild = rchild;
}
/*constructor*/
public HeroNode(int no,String name){
this.no=no;
this.name=name;
}
//ToString
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
/***
* 前序遍历
*/
public void preOrder(){
System.out.println(this);//根结点
if (this.lchild!=null)
this.lchild.preOrder();//递归-左子树
if (this.rchild!=null)
this.rchild.preOrder();//递归-右子树
}
/**
* 中序遍历
*/
public void inOrder(){
if (this.lchild!=null)
this.lchild.inOrder();//递归-左子树
System.out.println(this);//根结点
if (this.rchild!=null)
this.rchild.inOrder();//递归-右子树
}
/**
* 后序遍历
*/
public void postOrder(){
if (this.lchild!=null)
this.lchild.postOrder();//递归-左子树
if (this.rchild!=null)
this.rchild.postOrder();//递归-右子树
System.out.println(this);//根结点
}
}
2.2 二叉树定义
class BinaryTree{
private HeroNode root;//根结点
/*setter*/
public void setRoot(HeroNode root) {
this.root = root;
}
/**
* 前序遍历
*/
public void preOrder(){
if (this.root!=null)
this.root.preOrder();
else
System.out.println("tree is null!");
}
/**
* 中序遍历
*/
public void inOrder(){
if (this.root!=null)
this.root.inOrder();
else
System.out.println("tree is null!");
}
/**
* 后序遍历
*/
public void postOrder(){
if (this.root!=null)
this.root.postOrder();
else
System.out.println("tree is null!");
}
}
3 二叉树创建与遍历输出
public static void main(String[] args) {
//1-创建二叉树
BinaryTree binaryTree = new BinaryTree();
//2-创建结点
HeroNode a = new HeroNode(1, "宋江");
HeroNode b = new HeroNode(2, "吴用");
HeroNode c = new HeroNode(3, "卢俊义");
HeroNode d = new HeroNode(4, "林冲");
HeroNode e=new HeroNode(5,"关胜");
//3-手动创建二叉树
a.setLchild(b);
a.setRchild(c);
c.setRchild(d);
c.setLchild(e);
//4-设置binaryTree的根结点
binaryTree.setRoot(a);
//4-遍历二叉树
System.out.println("前序遍历");
binaryTree.preOrder();
System.out.println("中序遍历");
binaryTree.inOrder();
System.out.println("后序遍历");
binaryTree.postOrder();
}