When it comes to binary trees, there are several different types of traversals that can be done recursively. They are written in the order they are referenced, then visited (L = left child, V = visit node, R = right child).
- Bypass OK (LVR)
- Reverse Order Bypass (RVL)
- Order Bypass (VLR)
- Bypass in order (LRV)
Your code seems to follow a post-order workaround, but you get a few things mixed up. First, node is what you want to go through; data is what you want to visit. Secondly, you have no reason to return the node itself, as it is implemented. Your code does not allow the condition to say: "I am looking for this specific data, do you have it Mr. Node @ 0xdeadbeef? ', Which will be found with some definition of an additional search parameter.
The BST Academic Bypass prints only nodes. If you want to add a search function, this is another parameter, as well as an additional check of the correct node.
Here is a snippet:
// Academic public void traverse (Node root){ // Each child of a tree is a root of its subtree. if (root.left != null){ traverse (root.left); } System.out.println(root.data); if (root.right != null){ traverse (root.right); } } // Search with a valid node returned, assuming int public Node traverse (Node root, int data){ // What data are you looking for again? if(root.data == data) { return root; } if (root.left != null){ return traverse (root.left, data); } if (root.right != null){ return traverse (root.right, data); } return null; }
Makoto
source share