Problem Statement
leetcode problem link
Brute Force [Accepted]
# 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]:
def dfs(node, parent):
if not node:
if parent.val > val:
parent.left = TreeNode(val)
else:
parent.right = TreeNode(val)
return
if val > node.val:
dfs(node.right, node)
else:
dfs(node.left, node)
if not root:
return TreeNode(val)
dfs(root, val)
return root
Editorial
Approach 1: Recursion
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val > root.val:
# insert into the right subtree
root.right = self.insertIntoBST(root.right, val)
else:
# insert into the left subtree
root.left = self.insertIntoBST(root.left, val)
return root
Approach 2: Iteration
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
node = root
while node:
# insert into the right subtree
if val > node.val:
# insert right now
if not node.right:
node.right = TreeNode(val)
return root
else:
node = node.right
# insert into the left subtree
else:
# insert right now
if not node.left:
node.left = TreeNode(val)
return root
else:
node = node.left
return TreeNode(val)