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;
}
}