leetcode/0784_insert-into-a-binary-search-tree/python3/solution.py

32 lines
917 B
Python
Raw Normal View History

# 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