tags:

views:

57

answers:

1

I need the pseudocode for a C++ that will search through a tree to find the node with the value of “z”.

the function is given the root node to the tree to begin with. The tree has the property where each node has at most two children nodes. Each node has 3 properties: left child, right child, and value.

+2  A: 

The following pseudo-code will do what you want for a tree in ascending order.

def findval (node,lookfor):
    if node is null:
        return null
    if node.val is equal to lookfor:
        return node
    if node.val is less than lookfor
        return findval (node.right,lookfor)
    return findval (node.left,lookfor)

to be called with:

znode = findval (root, "z")

It will give you the node or null if no node exists.


Obviously, there's all sorts of enhancements you could make such as allowing a different order, or a callback comparison function, or allowing duplicate keys, but this is the canonical example of a binary tree search.

paxdiablo
this solution assumes that the right node has values greater than the left node, but my question does not say that.
fmunshi
But that invariably is the case because such trees are created as search structures. If it is not the case, then you need a depth first or breadth first search.
winwaed
The usual behaviour of a binary tree is ascending order. If that's not the case, simply switch around the conditions.
paxdiablo
@fmunshi, the whole point of a tree is to order the nodes. It's a reasonable assumption to make that the children would be ordered.
Mark Ransom
what is the reason for putting the check for node being NULL at the beginning?
fmunshi
@fmunshi, that's so it can elegantly handle an empty tree (where root is null).
paxdiablo