Insert into a Binary Search Tree

medium tree bst

Problem

Given the root of a binary search tree and a value to insert, return the root after inserting the value. Any valid BST structure that contains the inserted value is acceptable; you do not need to balance.

Inputroot = [4,2,7,1,3], val = 5
Output[4,2,7,1,3,5]
5 lands as the left child of 7.

def insert(root, val):
    if not root: return TreeNode(val)
    cur = root
    while True:
        if val < cur.val:
            if not cur.left: cur.left = TreeNode(val); break
            cur = cur.left
        else:
            if not cur.right: cur.right = TreeNode(val); break
            cur = cur.right
    return root
function insertIntoBST(root, val) {
  if (!root) return { val, left: null, right: null };
  let cur = root;
  while (true) {
    if (val < cur.val) {
      if (!cur.left) { cur.left = { val, left: null, right: null }; break; }
      cur = cur.left;
    } else {
      if (!cur.right) { cur.right = { val, left: null, right: null }; break; }
      cur = cur.right;
    }
  }
  return root;
}
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        TreeNode cur = root;
        while (true) {
            if (val < cur.val) {
                if (cur.left == null) { cur.left = new TreeNode(val); break; }
                cur = cur.left;
            } else {
                if (cur.right == null) { cur.right = new TreeNode(val); break; }
                cur = cur.right;
            }
        }
        return root;
    }
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
    if (!root) return new TreeNode(val);
    TreeNode* cur = root;
    while (true) {
        if (val < cur->val) {
            if (!cur->left) { cur->left = new TreeNode(val); break; }
            cur = cur->left;
        } else {
            if (!cur->right) { cur->right = new TreeNode(val); break; }
            cur = cur->right;
        }
    }
    return root;
}
Time: O(h) Space: O(1) iterative