FWNX- build a binary search tree using array - java version <<recursive>>

本文介绍了一种构建二叉搜索树的方法,并详细阐述了如何使用层次遍历算法对其进行遍历。通过实例代码展示了从数组构建树的过程,并实现了层次遍历功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test_kepler;

import test_kepler.TreefromA.Node;

public class BinarySTA {
	
	public class Node 
	{
		int value;
		public Node leftChild;
		public Node rightChild;
		public boolean isVisted;
		public Node(int i)
		{
			value = i;
			isVisted = false;
		}
		public void print()
		{
			System.out.print(this.value +" ~~ ");
		}
	}
	public Node AddTree(int a[],int left,int right)
	{
		if( right < left)
		{
			return null;
		}
		int mid = (left+right)/2;
		Node newNode = new Node(a[mid]);
		newNode.leftChild = AddTree(a,left,mid-1);
		newNode.rightChild = AddTree(a,mid+1,right);
		return newNode;
		
	}
	public void exe(int a[])
	{
		Node root = AddTree(a,0,a.length-1);
		BFS(root);
		
	}
	void BFS(Node root)
	{
		 qbytwostc testq = new qbytwostc<Node>();
		 testq.enQueue(root);
		 while(!testq.isEmpty())
		 {
			 Node head = (Node) testq.dequeue();
			 if(head.isVisted == false)
			 head.print();
			 
			 
			 
			 if(head.rightChild!=null && head.rightChild.isVisted == false)
			 {
				 testq.enQueue(head.rightChild);
			 }
			 
			 if(head.leftChild!=null && head.leftChild.isVisted == false)
			 {
				 testq.enQueue(head.leftChild);
			 }
		 }
	}
	
	public static void main(String[] args) {
		
		BinarySTA bsta = new BinarySTA();
		
		int a[] = {1,2,3,43,56,67,100};
		
		bsta.exe(a);
		
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值