开发者

Pseudo-code for search in binary tree

开发者 https://www.devze.com 2023-01-22 12:14 出处:网络
I need the pseudocode for a C++ that will search through a tree to find the node with the value of “z”.

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.


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.

If you want to avoid recursion, you can use the iterative solution:

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号