Iterate through binary search tree to find all leaves

Sti picture Sti · Nov 5, 2012 · Viewed 36.8k times · Source

I am pretty new to trees, and I am trying to create kind of a "leaf iterator". I'm thinking it should put all nodes that does not have a .left and .right value onto a stack, but I'm not sure how or even if it's the right thing to do. I have tried searching for it, but every example I come over starts with going to the leftmost leaf, and going p = node.parent, and I am avoiding linking to the node's parent.

I don't understand how I can repeatedlty start from the root and go through the vines without visiting the same vines over and over.

EDIT

I see people suggests using a recursive method to solve this, and I agree now. But I have been banging my head trying to find the solution for an iterator-class-way to do this for a while, and I still would like to know if that's possible, and how!

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Nov 5, 2012

Use recursion:

public void visitNode(Node node) {
    if(node.left != null) {
        visitNode(node.left);
    }
    if(node.right != null) {
        visitNode(node.right);
    }
    if(node.left == null && node.right == null) {
        //OMG! leaf!
    }
}

start it by supplying root:

visitNode(root);

In order to translate this into an Iterator<Node> you'll have to translate recursion to loop and then to traversal with state. Non-trivial, but should give you a lot of fun.