We are now ready to implement any of the tree traversal algorithms.
make sure to import ArrayList from java.util.ArrayList.
Pre Order Traversal
1
2
3
4
5
6
7
8
9
10
11
// the preOrder function, that is, it returns starting from the root, then left, then right
staticArrayList<Integer>preOrder(Nodenode,ArrayList<Integer>nodes){nodes.add(node.root);if(node.root!=0&&node.left!=null){preOrder(node.left,nodes);}if(node.root!=0&&node.right!=null){preOrder(node.right,nodes);}returnnodes;}
In Order Traversal
1
2
3
4
5
6
7
8
9
10
11
// the inOrder function, returns the left, then root, then right
staticArrayList<Integer>inOrder(Nodenode,ArrayList<Integer>nodes){if(node.root!=0&&node.left!=null){inOrder(node.left,nodes);}nodes.add(node.root);if(node.root!=0&&node.right!=null){inOrder(node.right,nodes);}returnnodes;}
Post Order Traversal
1
2
3
4
5
6
7
8
9
10
11
// the postOrder function returns the left, the right then the root
staticArrayList<Integer>postOrder(Nodenode,ArrayList<Integer>nodes){if(node.root!=0&&node.left!=null){postOrder(node.left,nodes);}if(node.root!=0&&node.right!=null){postOrder(node.right,nodes);}nodes.add(node.root);returnnodes;}
importjava.util.ArrayList;//the node class has a root, left, and right fields
classNode{publicintroot;publicNoderight;publicNodeleft;}classTree{publicstaticvoidmain(String[]args){Nodenode1=newNode();node1.root=5;Nodenode2=newNode();node2.root=4;Nodenode3=newNode();node3.root=6;Nodenode4=newNode();node4.root=1;Nodenode5=newNode();node5.root=2;node1.left=node2;node1.right=node3;node2.left=node4;node2.right=node5;ArrayList<Integer>result=newArrayList<Integer>();result=preOrder(node1,result);System.err.println(result);result.clear();result=inOrder(node1,result);System.err.println(result);result.clear();result=postOrder(node1,result);System.err.println(result);}//static methods so as to simply call without creating objects...
staticArrayList<Integer>preOrder(Nodenode,ArrayList<Integer>nodes){nodes.add(node.root);if(node.root!=0&&node.left!=null){preOrder(node.left,nodes);}if(node.root!=0&&node.right!=null){preOrder(node.right,nodes);}returnnodes;}staticArrayList<Integer>inOrder(Nodenode,ArrayList<Integer>nodes){if(node.root!=0&&node.left!=null){inOrder(node.left,nodes);}nodes.add(node.root);if(node.root!=0&&node.right!=null){inOrder(node.right,nodes);}returnnodes;}staticArrayList<Integer>postOrder(Nodenode,ArrayList<Integer>nodes){if(node.root!=0&&node.left!=null){postOrder(node.left,nodes);}if(node.root!=0&&node.right!=null){postOrder(node.right,nodes);}nodes.add(node.root);returnnodes;}}
The output:
[Running]cd"/Users/mikeck/Desktop/Java/"&& javac Tree.java && java Tree
[5, 4, 1, 2, 6][1, 4, 2, 5, 6][1, 2, 4, 6, 5][Done] exited with code=0 in 4.213 seconds
Thank you for reading. Feel free to contact me if you have any question, comment or suggestion.
🎉