First, define a node class:
Package Test;public class Node {private int data;private node Left;private node right;public node (int data) {This.data = d ATA;} public int GetData () {return data;} public void SetData (int data) {this.data = data;} Public Node GetLeft () {return to left;} public void Setleft (Node-left) {this.left = left;} Public Node GetRight () {return to right;} public void Setright (Node right) {this.right = right;}}
Two, define an algorithm implementation class:
Package Test;public class Findtree {private void visit (int data) {System.out.print (data+ "--");} public void preorder (Node root) {if (root = = null) {return;} Visit (Root.getdata ());p Reorder (Root.getleft ());p Reorder (Root.getright ()); public void inorder (Node root) {if (root = = null) {return;} Inorder (Root.getleft ()); Visit (Root.getdata ()); Inorder (Root.getright ());} public void Afterorder (Node root) {if (root = = null) {return;} Afterorder (Root.getleft ()); Afterorder (Root.getright ()); Visit (Root.getdata ());}}
Three, build a binary tree
Package test;public class testtree {public static void main (String[] args) {findtree ft = new findtree (); int[] array = { 12,76,35,22,16,48,90,46,9,40};int j = 0; Node root = new node (Array[j]); for (int i = 1; i< array.length; i++) {insert (Root, array[i]);} System.out.println ("Preorder----------------------------------"); Ft.preorder (root); System.out.println ("Inorder----------------------------------"); Ft.inorder (root); System.out.println ("Afterorder----------------------------------"); Ft.afterorder (root);} Private static void insert (Node root, int data) { //Two the left child node in the tree is smaller than the parent node, and the child node on the right is greater than the parent node if (Root.getdata () < data) {if (Root.getright () == null) {root.setright (New node (data));} else {insert (Root.getright (), data);}} eLse {if (Root.getleft () == null) {root.setleft (New node (data));} else {insert (Root.getleft (), data);}}} }
Four, print the result:
Preorder----------------------------------
12--9--76--35--22--16--48--46--40--90--
Inorder----------------------------------
9--12--16--22--35--40--46--48--76--90--
Afterorder----------------------------------
9--16--22--40--46--48--35--90--76--12--
Java implements three traversal algorithms (recursion) for two fork trees