public class Erchashu {
public static void main(String ards[])
{
//创建一颗二叉树
BinaryTerr binaryTerr=new BinaryTerr();
HeroNode root=new HeroNode(1, "金海");
HeroNode node2=new HeroNode(2, "铁林");
HeroNode node3=new HeroNode(3, "徐天");
HeroNode node4=new HeroNode(4, "燕三");
root.setLeft(node2);
root.setRight(node3);
node2.setLeft(node4);
binaryTerr.setRoot(root);
System.out.println("前序遍历");
binaryTerr.pre();
System.out.println("中序遍历");
binaryTerr.pro();
System.out.println("后序遍历");
binaryTerr.prh();
}
}
//构造二叉树
class BinaryTerr{
private HeroNode root; //生成一个根结点
public void setRoot(HeroNode root)
{
this.root=root;
}
public void pre(){
if(this.root!=null)
{
this.root.pre();
}
else{
System.out.println("二叉树为空不能遍历");
}
}
public void pro(){
if(this.root!=null)
{
this.root.pro();
}
else{
System.out.println("二叉树为空不能遍历");
}
}
public void prh(){
if(this.root!=null)
{
this.root.prh();
}
else{
System.out.println("二叉树为空不能遍历");
}
}
}
//创建二叉树结点
class HeroNode{
private int no;
private String name;
private HeroNode left; //左孩子默认为空
private HeroNode right; //右孩子默认为空
public HeroNode(int no,String name) //构造函数
{
this.no=no;
this.name=name;
}
//给当前结点挂上左孩子
public void setLeft(HeroNode left) {
this.left = left;
}
//给当前结点挂上右孩子
public void setRight(HeroNode right) {
this.right = right;
}
@Override
public String toString(){
return "HeroNode [no="+no+",name="+name+"]";
}
//先序遍历
public void pre(){
System.out.println(this.toString());
if(this.left!=null)
{
this.left.pre();
}
if(this.right!=null)
{
this.right.pre();
}
}
public void pro(){
if(this.left!=null)
{
this.left.pre();
}
System.out.println(this.toString());
if(this.no==1)
{
System.out.println("找到了");
return;
}
if(this.right!=null)
{
this.right.pre();
}
}
public void prh(){
if(this.left!=null)
{
this.left.pre();
}
if(this.right!=null)
{
this.right.pre();
}
System.out.println(this.toString());
}
}
Java构造二叉树及其三种遍历方式
最新推荐文章于 2024-02-05 17:42:06 发布