Insert into a Binary Search Tree

LeetCode Q 701 - Insert into a Binary Search Tree

Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

Solution:

Code: Recursion

public TreeNode insertIntoBST(TreeNode root, int val) {
  if (root == null) return new TreeNode(val);

  if (root.val > val) root.left = insertIntoBST(root.left, val);
  if (root.val < val) root.right = insertIntoBST(root.right, val);

  return root;
}

Code: Iteration

public TreeNode insertIntoBST(TreeNode root, int val) {
  if (root == null) return new TreeNode(val);
  
  TreeNode n = new TreeNode(val);
  
  TreeNode curr = root;
  
  while (true) {
    if (curr.val < val) {
      if (curr.right != null) {
        curr = curr.right;
      } else {
        curr.right = n;
        break;
      }
    } else {
      if (curr.left != null) {
        curr = curr.left;
      } else {
        curr.left = n;
        break;
      }
    }
  }
  
  return root;
}

   Reprint policy


《Insert into a Binary Search Tree》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC