Skip to content

Instantly share code, notes, and snippets.

@parcar
Created August 15, 2019 17:31
Show Gist options
  • Select an option

  • Save parcar/614f185fcdb0defbb4336705f24a7aa4 to your computer and use it in GitHub Desktop.

Select an option

Save parcar/614f185fcdb0defbb4336705f24a7aa4 to your computer and use it in GitHub Desktop.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
if (root is None):
return
ms = []
ms.append(root)
while (len(ms)):
curr = ms.pop()
if (curr.val < val and curr.right):
ms.append(curr.right)
elif (curr.val > val and curr.left):
ms.append(curr.left)
else:
if(val > curr.val and curr.right == None):
curr.right = TreeNode(val)
return root
elif(val < curr.val and curr.left == None):
curr.left = TreeNode(val)
return root
else:
print("Error")
return
'''
Runtime: 104 ms, faster than 50.03% of Python online submissions for Insert into a Binary Search Tree.
Memory Usage: 15.8 MB, less than 86.67% of Python online submissions for Insert into a Binary Search Tree.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment