Sorting rules for binary tree algorithms:
1. Select the first element as the root node
2, after if the element is greater than the root node placed in the right subtree, if the element is small root node, then put in Zuozi
3, finally follow the way of the middle sequence traversal output, you can get the result of sorting (left-to-root-right)
The core class of the binary tree algorithm, which only provides methods for adding and printing output
Package com.lym.binarytree;/** * Binary tree Algorithm collation: * 1, select the first element as the root node * 2, then if the element is greater than the root node is placed in the right subtree, if the element is small root node, then placed in the left subtree * 3, and finally follow the way of the middle sequence traversal output , you can get a sorted result (left-to-root-right) * * @author Administrator * */public class BinaryTree {private node root;//root node//Add node, provide external access public void Add (int data) {if (root = null) {root = new Node (data);} else {Root.addnode (data)}} The output node, which provides external access to public void print () {if (root! = null) {Root.printnode ();}} The branch node class nodes {private node leftnode;private node Rightnode;private int data;public node (int data) {this.data = data;} Add node public void AddNode (int data) {if (This.data > data) {//Add on left if (This.leftnode = = null) {This.leftnode = new No De (data);} else {this.leftNode.addNode (data);}} else if (this.data <= data) {if (This.rightnode = = null) {This.rightnode = new Node (data);} else {This.rightNode.addNod E (data);}}} Output all nodes//middle order traverse public void Printnode () {if (This.leftnode! = null) {This.leftNode.printNode ();} System.out.print (This.data + "");//The output statement ends with a subsequent traversal of if (This.rightnode ! = null) {This.rightNode.printNode ();}}}}
Test class of Binary tree
Package com.lym.binarytree;/** * Binary Tree Test class * * @author Administrator * */public class Binarytreedemo {public static void Main (string[] args) {BinaryTree bt = new BinaryTree (); Bt.add (3); Bt.add (5); Bt.add (2); Bt.add (1); Bt.add (4); Bt.add (8); Bt.add (Bt.add); Bt.add (6); Bt.add (9); Bt.print ();}}
java-Two fork Tree algorithm