您的位置:首页 > 编程语言 > Java开发

java实现简单二叉树排序

2018-01-04 09:41 579 查看
public class Test01{public static void main(String args[]){BinaryTree bt = new BinaryTree();bt.add(3);bt.add(7);bt.add(9);bt.add(2);bt.add(4);bt.add(12);bt.add(8);bt.add(6);bt.add(21);bt.add(0);bt.add(4);bt.print();}};class BinaryTree{class Node{private Comparable data;//自动装箱,Integer转为Comparableprivate Node left;private Node right;public Node(Comparable data){this.data = data;}public void addNode(Node newNode){//添加新节点if(newNode.data.compareTo(this.data)<0){if(this.left == null){this.left = newNode;}else{this.left.addNode(newNode);}}if(newNode.data.compareTo(this.data)>=0){if(this.right == null){this.right = newNode;}else{this.right.addNode(newNode);}}}public void printNode(){//中序输出if(this.left!=null){this.left.printNode();}System.out.println(this.data+"  ");if(this.right!=null){this.right.printNode();}}};private Node root;//根public void add(Comparable data){//添加元素Node newNode = new Node(data);if(root == null){//如果没有根节点root = newNode;}else{root.addNode(newNode);}}public void print(){root.printNode();}};
简单实现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java