SDE & MLE Prep

701. Insert into a Binary Search Tree

Problem

Insert val (not already present) into a BST and return the root of a valid BST. Any valid result is accepted.

Example: [4,2,7,1,3], val = 5 → [4,2,7,1,3,5]

Walk down as in a search until you fall off the tree; attach the new node there as a leaf. (Any valid BST is accepted; leaf insertion is the simplest.)

Complexity: O(h).

class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        node = TreeNode(val)
        if not root:
            return node
        cur = root
        while True:
            if val < cur.val:
                if not cur.left:
                    cur.left = node
                    return root
                cur = cur.left
            else:
                if not cur.right:
                    cur.right = node
                    return root
                cur = cur.right