32 lines
917 B
Python
32 lines
917 B
Python
# 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
|