mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-03 07:15:04 -04:00
Create bst_insert_node.py
This commit is contained in:
parent
fb8081ae42
commit
8e8f934d12
1 changed files with 42 additions and 0 deletions
42
trees/bst_insert_node.py
Normal file
42
trees/bst_insert_node.py
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
|
def bst_insert_iterative(root, val):
|
||||||
|
|
||||||
|
new_node = Node(val)
|
||||||
|
this_node = root
|
||||||
|
|
||||||
|
while this_node:
|
||||||
|
|
||||||
|
if val > this_node.val:
|
||||||
|
if not this_node.right:
|
||||||
|
this_node.right = new_node
|
||||||
|
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):
|
||||||
|
|
||||||
|
if not root:
|
||||||
|
return Node(val)
|
||||||
|
|
||||||
|
if val > root.val:
|
||||||
|
root.right = self.insertIntoBST(root.right, val)
|
||||||
|
|
||||||
|
else:
|
||||||
|
root.left = self.insertIntoBST(root.left, val)
|
||||||
|
|
||||||
|
return root
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue