feat(0784_insert-into-a-binary-search-tree): add py3 soln
This commit is contained in:
31
0784_insert-into-a-binary-search-tree/python3/solution.py
Normal file
31
0784_insert-into-a-binary-search-tree/python3/solution.py
Normal file
@@ -0,0 +1,31 @@
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
|
||||
if root == None:
|
||||
return TreeNode(val)
|
||||
|
||||
current = root
|
||||
parent = None
|
||||
|
||||
while True:
|
||||
if val < current.val:
|
||||
if current.left == None:
|
||||
current.left = TreeNode(val)
|
||||
break
|
||||
|
||||
parent = current
|
||||
current = current.left
|
||||
elif val >= current.val:
|
||||
if current.right == None:
|
||||
current.right = TreeNode(val)
|
||||
break
|
||||
|
||||
parent = current
|
||||
current = current.right
|
||||
|
||||
return root
|
||||
Reference in New Issue
Block a user