Tree: The characteristic of a tree structure is that a node can have multiple direct successors and is a commonly used nonlinear structure.
Binary tree: Combining the advantages of an ordered array and a linked list, finding data in a tree is as fast as finding it in an ordered array, adding and deleting data as fast as in a linked list.
When inserting an operation, the binary tree starts at the root node, is larger than the parent node, inserts to the left, and is smaller than the parent node to the right.
The following is a list of two fork trees implemented:
Node.java
PackageBTree;/*** Node class of linked list binary tree*/ Public classNode {intdata; Node Leftchild; Node Rightchild; //initializing the root node PublicNode () {Data= 0; Leftchild=NULL; Rightchild=NULL; } //Initializing Nodes PublicNode (intdata) { This. data =data; Leftchild=NULL; Rightchild=NULL; }}
Linkofbtree.java
PackageBTree;/** * @author* Linked list to achieve two-fork tree * Three traversal methods: root traversal, root traversal, after root traversal*/ Public classlinkofbtree {Node root=NULL; //Initialize binary tree PublicLinkofbtree (intdata) {Root=NewNode (data); } //new Node Public voidAddintdata) {Node Node=NewNode (data); Node Temp=Root; while(true){ if(Temp.data >=data) { if(Temp.leftchild! =NULL) Temp=Temp.leftchild; Else{temp.leftchild=node; Break; } }Else{ if(Temp.rightchild! =NULL) Temp=Temp.rightchild; Else{temp.rightchild=node; Break; } } } } /**Print binary tree: Recursive *node: initial data for root node * * First root traversal*/ Public voidDisplayrootfirst (node node) {System.out.println ("Node Value:" +node.data); if(Node.leftchild! =NULL) Displayrootfirst (node.leftchild); if(Node.rightchild! =NULL) Displayrootfirst (node.rightchild); } /*** Middle root traverse binary tree*/ Public voidDisplayrootmid (node node) {if(Node.leftchild! =NULL) Displayrootmid (node.leftchild); System.out.println ("Node Value:" +node.data); if(Node.rightchild! =NULL) Displayrootmid (node.rightchild); } /*** Posterior root traverse binary tree*/ Public voidDisplayrootlast (node node) {if(Node.leftchild! =NULL) Displayrootlast (node.leftchild); if(Node.rightchild! =NULL) Displayrootlast (node.rightchild); System.out.println ("Node Value:" +node.data); } Public Static voidMain (string[] a) {Linkofbtree tree=NewLinkofbtree (10); Tree.add (8); Tree.add (7); Tree.add (3); Tree.add (11); Tree.add (3); Tree.add (20); Tree.add (26); Tree.add (11); System.out.println ("------Root traversal------"); Tree.displayrootfirst (Tree.root); System.out.println ("------Root traversal------"); Tree.displayrootmid (Tree.root); System.out.println ("------After root traversal------"); Tree.displayrootlast (Tree.root); }}
Java data structure: two fork Tree