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.
精彩评论