返回信息流/****从键盘输入数字建立一个二叉树,计算数的节点数、叶子数、检测树是否是一个折半查找树*******/
/****Queue.java****/
public class Queue {
private java.util.LinkedList list=new java.util.LinkedList();
public Queue() {
}
public boolean isEmpty(){
return list.isEmpty();
}
public Object dequeue(){
return list.removeFirst();
}
public void enqueue(Object el){
list.addLast(el);
}
public String toString(){
return list.toString();
}
}
/******IntBSTNode.java****/
public class IntBSTNode {
protected int key;
protected IntBSTNode left,right;
public IntBSTNode() {
left=right=null;
}
public IntBSTNode(int el){
this(el,null,null);
}
public IntBSTNode(int el,IntBSTNode lt,IntBSTNode rt){
key=el;left=lt;right=rt;
}
public void visit(){
System.out.println(key+" ");
}
}
/*******IntBST.java******/
public class IntBST{
protected IntBSTNode root;
public IntBST() {
root=null;
}
public void preorder(){
preorder(root);
}
protected void preorder(IntBSTNode p){
//IntBSTNode preorder(IntBSTNode p) {
if (p != null) {
p.visit();
preorder(p.left);
preorder(p.right);
}
}
// }
public void count(){
count(root);
}
protected int count(IntBSTNode p){
int n=0;
if(p!=null){
n=n+1;
count(p.left);
count(p.right);
}
return n;
}
/*public void countleaf(){
countleaf(root);
}*/
public int countleaf(IntBSTNode p){
int n=0;
IntBSTNode b=root;
Queue queue=new Queue();
if(b!=null){
queue.enqueue(b);
while(!queue.isEmpty()){
b=(IntBSTNode)queue.dequeue();
if(p.left!=null)queue.enqueue(p.left);
if(p.right!=null)queue.enqueue(p.right);
if(p.left==null&&p.right==null)n++;
}
}
return n;
}
就写到这儿了,,有点儿写不下去,,现在想从键盘输入数来建树,是不是还要另建一个class?还是继续在IntBST里面写?main函数建在哪儿?嗯……有些混乱,希望大家帮着讨论一下。
这是一条镜像帖。来源:北邮人论坛 / soft-design / #14412同步于 2007/1/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
SoftDesign机器人发帖
JAVA数据结构二叉树基本操作请教
yuebixiong
2007/1/10镜像同步9 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
偶太无聊了
protected int count(IntBSTNode p){
return p == null ? 0 : count(p.left) + count(p.right) + 1;
}
继续
public void addToTree(int el){
IntBSTNode p=root,prev=null;
while(p!=null){
prev=p;
if(p.key<el) p=p.right;
if(p.key>el) p=p.left;
}
if(root==null)root=new IntBSTNode(el);
else if(prev.key<el)prev.right=new IntBSTNode(el);
else if(prev.key>el)prev.left=new IntBSTNode(el);
}
public void readKey() throws IOException {
String str="";
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
str=buffer.readLine();
StringTokenizer st=new StringTokenizer(str," ");
while(true){
if(st.hasMoreTokens()){
addToTree(Integer.parseInt(st.nextToken()));
}
}
}
我这是写了一个从键盘输入添加到树的method
可以么????
如果只是测试用的话,另外写个类,做一下命令行下的菜单,随便弄一下就好了,不需要太复杂的东西
【 在 yuebixiong 的大作中提到: 】
: 继续
: public void addToTree(int el){
: IntBSTNode p=root,prev=null;
: ...................