二叉树排序算法的实现
//节点类
public class Node { private Node left; private Node right; private int data; public Node(int data){ this.data=data; } public void addNode(Node newNode){ if(newNode.data=this.data){ if(this.right==null){ this.right=newNode; }else{ this.right.addNode(newNode); } } } public void printNode(){ if(this.left!=null){ this.left.printNode(); } System.out.print(this.data+"\t"); if(this.right!=null){ this.right.printNode(); } }}
//声明一个二叉树
class BinaryTree { private Node root; public void add(int data){ Node newNode=new Node(data); if(root==null){ root=newNode; }else{ root.addNode(newNode); } } public void print(){ this.root.printNode(); } }
//测试二叉树排序TestBinaryTree
public class TestBinaryTree { public static void main(String[] args) { BinaryTree bt = new BinaryTree(); bt.add(3); bt.add(4); bt.add(5); bt.add(6); bt.add(0); bt.add(7); bt.add(1); bt.add(9); bt.add(-3); bt.print(); }}
结果是
-3 0 1 3 4 5 6 7 9