二叉树的基本遍历程序

package main;

class Node{
	public int data;
	public Node left;
	public Node right;
	public Node(int data){
		this.data=data;
		this.left=null;
		this.right=null;
	}
}

public class BinaryNode {
   public Node root;
   public BinaryNode(){
	   root=null;
   }
   //插入节点
   public void insert(int data)
   {
	   Node newNode=new Node(data);
	   if(root==null)
	   {
		  root=newNode; 
	   }
	   else{
	   Node current=root;
	   Node parent;
	   while(true)
	   {
		   parent=current;
		   if(data<current.data)
		   {
			   current=current.left;
			   if(current==null)
			   {
				   parent.left=newNode;
				   return;
			   }
		   }
		   else
		   {
			   current=current.right;
			   if(current==null)
			   {
				   parent.right=newNode;
				   return;
			   }
		   }
	   }
   }
  }
   //创建二叉树
   public void  buidTree(int[] data)
   {
	   for(int i=0;i<data.length;i++)
	   {
		   insert(data[i]);
	   }
   }
   //递归法中序遍历
   public void order(Node node)
   {
	   if(node!=null)
	   {
		  order(node.left);
		  System.out.print(node.data+" ");
		  order(node.right);
	   }
   }
   // 递归法前序遍历
   public void before(Node node)
   {
	   
	   if(node!=null)
		{
		  System.out.print(node.data+" ");
	      before(node.left);
	      before(node.right);
		}
   }
   // 递归后序遍历
   public void later(Node node)
   {
	   if(node!=null)
	   {   
		   later(node.left);
		   later(node.right);
		   System.out.print(node.data+" ");
	   }
   }
   public static void main(String[] args){
	   BinaryNode bitTree=new BinaryNode();
	   int[] data={2,8,7,4,9,3,1,6,7,5};
	   bitTree.buidTree(data);
	
	   //前序遍历结果
	   System.out.println("前序遍历结果");
	   bitTree.before(bitTree.root);
	   System.out.println();
	   
	    // 中序遍历结果
	   System.out.println("中序遍历结果");
	   bitTree.order(bitTree.root);
	   System.out.println();
	   
	   // 后序遍历结果
	    System.out.println("后序遍历结果");
	    bitTree.later(bitTree.root);
	    System.out.println();
   }
}

输出结果:

前序遍历结果
2 1 8 7 4 3 6 5 7 9 
中序遍历结果
1 2 3 4 5 6 7 7 8 9 
后序遍历结果
1 3 5 6 4 7 7 9 8 2 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伏特加的滋味

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值