Here you can see two important methods for binary tree nodes. The difference between the two is that bst_contains checks whether the wanted value is greater or less than the node value, before calling itself on the node's left or right child.
def contains(node, value):
''' (BTNode, object) -> value
Return whether tree rooted at node contains value.
>>> contains(None, 5)
False
>>> contains(BTNode(5, BTNode(7), BTNode(9)), 7)
True
'''
if node is None:
return False
else:
return (node.data == value or
contains(node.left, value) or
contains(node.right, value))
def bst_contains(node, value):
''' (BTNode, object) -> value
Return whether tree rooted at node contains value.
Assume node is the root of a BST.
>>> contains(None, 5)
False
>>> contains(BTNode(7, BTNode(5), BTNode(9)), 5)
True
'''
assert node is None or isinstance(node, BTNode), (
'Not a BTNode: {}'.format(node))
if node is None:
return False
elif node.data > value:
return bst_contains(node.left)
elif node.data < value:
return bst_contains(node.right)
else:
return True
We also looked at the recursive functions inorder, preorder, and postorder for visiting tree nodes.
Inorder visits the left tree, the node, then the right tree. Preorder visits the node, the left tree, then the right tree, and postorder visits the left tree, the right tree, then the node.
No comments:
Post a Comment