Skip to content

Instantly share code, notes, and snippets.

@sahid
Created February 18, 2013 18:50
Show Gist options
  • Save sahid/4979645 to your computer and use it in GitHub Desktop.
Save sahid/4979645 to your computer and use it in GitHub Desktop.
Insert into a BST Python
def insert(root, node):
curr = root # Keeps the root of the tree.
while curr:
parent = curr
if node.key < curr.key:
curr = node.left
else:
curr = node.right
node.parent = parent
if node.parent is None:
return node # New root of an empty tree.
if node.key < node.parent.key:
node.parent.left = node
else
node.parent.rigth = node
return root # Returns the root of the tree.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment