二叉排序树的基本操作

数据结构用的是C语言描述,初学java,用java实现

package ldm;
import java.util.*;
class BinaySortNode{
	public int key;
	public BinaySortNode lc;
	public BinaySortNode rc;
	public BinaySortNode(int k) {
		key=k;lc=null;rc=null;
	}
}
class BinarySortTree{
	public BinaySortNode root;
	public BinarySortTree(int k) {
		root=new BinaySortNode(k);
	}
	public BinaySortNode search(BinaySortNode node,int key) {
		if(node==null||key==node.key) return node;
		else if(key<node.key) return search(node.lc,key);
		else return search(node.rc,key);
	}
	public boolean insert(int key) {
		BinaySortNode p,pre;
		boolean vis=false;
		p=root;pre=root;
		while(p!=null&&key!=p.key) {
			pre=p;
			if(key<p.key) p=p.lc;
			else p=p.rc;
		}
		if(p!=null&&key==p.key) {
			vis=false;
			return false;
		}
		else {
			p=new BinaySortNode(key);
			if(key<pre.key) pre.lc=p;
			else pre.rc=p;
			return true;
		}
	}
}
public class Main {
	public static void main(String[] argc) {
	     Scanner cin=new Scanner(System.in);
	     int n=cin.nextInt(),k=cin.nextInt();
	     BinarySortTree tree=new BinarySortTree(cin.nextInt());
	     for(int i=1;i<n;i++) tree.insert(cin.nextInt());
	     BinaySortNode flag;
	     for(int i=0;i<k;i++) {
	    	 flag=tree.search(tree.root,cin.nextInt());
	    	 if(flag!=null) System.out.print("1 ");
	    	 else System.out.print("0 ");
	     }
	     System.out.println();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41061455/article/details/80775166