mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update bst_insert_node.py
This commit is contained in:
parent
a3ce5db3a5
commit
cb2909d421
@ -5,38 +5,35 @@
|
|||||||
|
|
||||||
def bst_insert_iterative(root, val):
|
def bst_insert_iterative(root, val):
|
||||||
|
|
||||||
new_node = Node(val)
|
node = root
|
||||||
this_node = root
|
while node:
|
||||||
|
|
||||||
while this_node:
|
if val > node.val:
|
||||||
|
if not node.right:
|
||||||
|
node.right = Node(val)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
node = node.right
|
||||||
|
|
||||||
|
else:
|
||||||
|
if not node.left:
|
||||||
|
node.left = Node(val)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
node = node.left
|
||||||
|
|
||||||
if val > this_node.val:
|
|
||||||
if not this_node.right:
|
|
||||||
this_node.right = new_node
|
|
||||||
return root
|
return root
|
||||||
else:
|
|
||||||
this_node = this_node.right
|
|
||||||
|
|
||||||
else:
|
|
||||||
if not this_node.left:
|
|
||||||
this_node.left = new_node
|
|
||||||
return this_node
|
|
||||||
else:
|
|
||||||
this_node = this_node.left
|
|
||||||
|
|
||||||
return new_node
|
|
||||||
|
|
||||||
|
|
||||||
def bst_insert_recursive(root, val):
|
def bst_insert_recursive(root, val):
|
||||||
|
|
||||||
if not root:
|
if root is None:
|
||||||
return Node(val)
|
return Node(val)
|
||||||
|
|
||||||
if val > root.val:
|
if val > root.val:
|
||||||
root.right = self.insertIntoBST(root.right, val)
|
root.right = self.bst_insert_recursive(root.right, val)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
root.left = self.insertIntoBST(root.left, val)
|
root.left = self.bst_insert_recursive(root.left, val)
|
||||||
|
|
||||||
return root
|
return root
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user