Java实现二叉树及其操作

使用Java实现二叉树及其遍历操作

实现二叉树 首先实现二叉树的结点元素 此处结点元素定义为树结点的值和二叉树结点类型的左孩子和右孩子

操作为构建、遍历操作(前序遍历、中序遍历、后续遍历)

代码如下


public class BinTree {

	//二叉树的定义、构建以及前中后序遍历
	int val;//the value of the node
	BinTree lchild;//左子树
	BinTree rchild;//右子树
	
	BinTree(int x)
	{
		this.val=x;
	}
	
	public void Pretraverse(BinTree bt)//二叉树的前序遍历:root-left-right
	{
		BinTree temp=bt;
		if(temp!=null)
		{
			System.out.print(temp.val+"->");
			Pretraverse(bt.lchild);
			Pretraverse(bt.rchild);
		}
			
	}
	public void Intraverse(BinTree bt)//二叉树的中序遍历:left-root-right
	{
		BinTree temp=bt;
		if(temp!=null)
		{
			Intraverse(bt.lchild);
			System.out.print(temp.val+"->");
			Intraverse(bt.rchild);
		}
			
	}
	public void Posttraverse(BinTree bt)//二叉树的后序遍历:left-right-root
	{
		BinTree temp=bt;
		if(temp!=null)
		{		
			Posttraverse(bt.lchild);
			Posttraverse(bt.rchild);
			System.out.print(temp.val+"->");
		}
			
	}
	public static void main(String[] args) {
		
		//构建二叉树
		BinTree root=new BinTree(100);
		
		root.lchild=new BinTree(50);
		root.rchild=new BinTree(130);
		
		root.lchild.lchild=new BinTree(35);
		root.lchild.rchild=new BinTree(55);
		
		root.rchild.lchild=new BinTree(105);
		root.rchild.rchild=new BinTree(135);
		
		//遍历
		System.out.println("前序遍历");
		root.Pretraverse(root);
		System.out.println("\\");
		
		
		System.out.println("中序遍历");
		root.Intraverse(root);
		System.out.println("\\");
		
		
		System.out.println("后序遍历");
		root.Posttraverse(root);
		System.out.println("\\");
	}

}

运行结果:

前序遍历
100->50->35->55->130->105->135->\
中序遍历
35->50->55->100->105->130->135->\
后序遍历
35->55->50->105->135->130->100->\

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章