Define binary operation class Binarytree{class node{private node left;//index private node right;//index private comparable data;public node (comparable<?> data) {this.data = data;} Binary data comparison, large placed on the right, small on the left public void AddNode (Node newNode) {//on the Left if (NewNode.data.compareTo (this.data) <= 0) {if ( This.left==null) {this.left = NewNode;} Else{this.left.addnode (NewNode);//downward continues to judge that the pointer points to the next}}system.out.println ("This.data=" +this.data); System.out.println ("Newnode.data=" +newnode.data); System.out.println ("----------------->");//On the Right if (NewNode.data.compareTo (This.data) > 0) {if (This.right = = NULL) {this.right = NewNode;} Else{this.right.addnode (NewNode);//downward continues to judge that the pointer points to the next}}}//in the sequence of printing data public void Printnode () {if (this.left! = NULL)//existence left exponent { This.left.printNode (); Continue looking for the following left exponent}system.out.println (this.data); if (this.right! = NULL)//exists right exponent {this.right.printNode ();//continues to find the right exponent below, The pointer points to the next}}} private Node root;public void Add (comparable data)//Accept the datastore {node NewNode = new Node (data); if (this.root = = null) { This.root = NewNode; Set as root node}Else{this.root.addnode (NewNode);}} public void print () {//outputs all the root node data this.root.printNode ();}} public class ComparaDemo3 {public static void main (String args[]) {BinaryTree BT = new BinaryTree (); Bt.add (3); Bt.add (4); BT . Add (8); Bt.add (1); Bt.add (6); Bt.add (3); bt.add; Bt.print ();}}
This method is generally not recommended, direct recommendation, implements comparable, implement Comparato () method
Java:comparable Comparator, define binary operation class