二叉排序树Java版

来源:互联网 发布:超浓密睫毛膏 知乎 编辑:程序博客网 时间:2024/04/29 10:49
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。

1.节点
public class Node<T extends Comparable<T>>{private T data;//结点的值private Node left;//左结点private Node right;//右结点public Node(T data){this.data=data;}//添加节点public void addChild(Node<T> child){if(child==null)//如果结点为空直接返回return;else{//当前结点的值和要添加节点的值比较,如果大于childif(this.compareTo(child)>=0){//判断当前对象的左结点是否为空,如果为空直接添加if(this.left==null){this.left=child;}else//不为空,用当前对象的左结点继续和child比较{this.left.addChild(child);}}else{if(this.right==null){this.right=child;}else{this.right.addChild(child);}}}}//中序遍历public void printNode(){if(this.left!=null){this.left.printNode();}System.out.println(this.data.toString());if(this.right!=null){this.right.printNode();}}//重写compareTo方法private int compareTo(Node<T> node){ //调用的是T的实际类型的compareTo方法return this.data.compareTo(node.data);}  }


2.二叉树和根节点
public class BinaryTree< E extends Comparable<E>>{private Node<E> root;//根节点//向树中添加结点public void addElement(E element){if(element==null)return;//创建NodeNode<E> node=new Node<E>(element);if(this.root==null)//如果根节点为空,将当前结点设为根节点{this.root =node;}else{root.addChild(node);//通过根节点向二叉树中添加结点}}//打印二叉树public void printBinaryTree(){          if(this.root == null)        {              System.out.println("当前为空对象,无法打印。");              return;          }          this.root.printNode();  }public Node<E> getRoot() {return root;}public void setRoot(Node<E> root){this.root = root;}}

3.主函数
public class BTNodeTest {public static void main(String[] args) {BinaryTree<Integer> root=new BinaryTree<Integer>();root.addElement(5);root.addElement(2);root.addElement(3);root.addElement(1);root.addElement(4);root.printBinaryTree();}}

来源:http://will-turner.iteye.com/blog/1689177

0 0
原创粉丝点击