java dsf搜索,

package suanfa;

import java.util.Random;

public class Nodesearch {
    int len=0;
	public void dfs(Node node,int value){
		int a[]=new int[1000];
		if(node==null){
			System.out.print("this is the empty tree!");
		}
		if(node.getLchild()==null&&node.getRchild()==null){
			if(node.getValue()!=value){
				return;
			}
			else{
				System.out.println("A path find:");
				for(int i=0;i<len;i++){
				 System.out.println("the value is "+a[i]);
				}
			}
		}
		a[len++]=node.getValue();
		if(node.getLchild()!=null){
			dfs(node.getLchild(),value-node.getValue());
		}
		if(node.getRchild()!=null){
			dfs(node.getRchild(),value-node.getValue());
		}
		len--;
	}
	public static void main(String[] args) {
		
		Nodesearch dfs=new Nodesearch();
		int[]a=dfs.producearray(5);
		Node node=dfs.setbinarytree(a);
		int k=15;
		dfs.dfs(node, k);
		
	}
	public int[] producearray(int n){
		int[] a=new int[n];
		Random rand = new Random();
		for(int i=0;i<n;i++){
		 a[i]=rand.nextInt(10);
		}
		return a;
	}
	
	public Node setbinarytree(int[] a ){
		Node node=new Node();
		node.setValue(a[0]);
		for(int i=1;i<a.length;i++){
			insert(node,a[i]);
			
		}
		return node;
		
		
	}
	public void insert(Node node,int value){
		if(value>=node.getValue()){
			if(node.getRchild()==null){
				Node nodenew=new Node();
				nodenew.setValue(value);
				node.setRchild(nodenew);
			}
			else{
				insert(node.getRchild(),value);
			}
		}
		else{
			if(node.getLchild()==null){
				Node nodenew=new Node();
				nodenew.setValue(value);
				node.setLchild(nodenew);
			}
			else{
				insert(node.getLchild(),value);
			}
		}
	}
}

 node类是:

package suanfa;

public class Node {
   
	private int value;
	private Node lchild;
	private Node rchild;
	public int getValue() {
		return value;
	}
	public Node getLchild() {
		return lchild;
	}
	public Node getRchild() {
		return rchild;
	}
	public void setValue(int value) {
		this.value = value;
	}
	public void setLchild(Node lchild) {
		this.lchild = lchild;
	}
	public void setRchild(Node rchild) {
		this.rchild = rchild;
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值