Java:comparable Comparator, define binary operation class

Source: Internet
Author: User
Tags comparable

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.