看了二叉查找树就自己用java写了个。。写插入时。犯了个很二的错误,就不提了,使用的是先序遍历。
package com.bst; public class TreeNode<E extends Number> {//节点 private E element; //root private TreeNode<E> left; private TreeNode<E> right; public TreeNode(E e){ element=e; } public TreeNode(){} public boolean insert(E e){ //如果tree为空,则给root赋值 if(this.element==null){ this.setElement(e); return true; } TreeNode<E> current=this; //parent 在插入e时会用到 TreeNode<E> parent=this; while(current!=null) { //判断与root元素大小 if(e.floatValue()<current.element.floatValue()) { parent=current; current=current.left; //Go ledt 进入左子树!下同 }else if(e.floatValue()>current.element.floatValue()) { parent=current; current=current.right; }else return false; } //current=new TreeNode<E>(e) 给current指向,但不是其节点的子树所指。所以一直用parent if(e.floatValue()<parent.element.floatValue()) parent.left=new TreeNode<E>(e); else parent.right=new TreeNode<E>(e); return true; } public boolean search(E e){ TreeNode<E> current=this; while(current!=null){ if(e.floatValue()<current.element.floatValue()) current=current.left; else if(e.floatValue()>current.element.floatValue()) current=current.right; else return true; } return false; } public void print(){ if(left!=null) left.print(); System.out.print(element+" "); if(right!=null){ right.print(); } } public E getElement() { return element; } public void setElement(E element) { this.element = element; } public TreeNode<E> getLeft() { return left; } public void setLeft(TreeNode<E> left) { this.left = left; } public TreeNode<E> getRight() { return right; } public void setRight(TreeNode<E> right) { this.right = right; } public static void main(String[] args) { TreeNode<Integer> integer =new TreeNode<Integer>(); Integer[] intes={9,6,20,8,5,16,23}; for(Integer i:intes) integer.insert(i); //System.out.println(integer.search(9)); integer.print(); } }