Insert into a Binary Search Tree

Problem: https://leetcode.com/problems/insert-into-a-binary-search-tree/description/

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.
For example, 
Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5
You can return this binary search tree:
         4
       /   \
      2     7
     / \   /
    1   3 5
This tree is also valid:
         5
       /   \
      2     7
     / \   
    1   3
         \
          4

Best is to traverse down the tree using the BST characteristic ("binary") which should take Log(N). When you hit a node for which the corresponding right or left node (based on "val") is null, insert the new node right there. Runs in O(Log(N)). Code is below, thanks, Boris.


public class Solution
{
 public TreeNode InsertIntoBST(TreeNode root, int val)
 {
  _InsertIntoBST(root, val);
  return root;
 }

 private void _InsertIntoBST(TreeNode root, int val)
 {
  if (root == null) return;
  if (val < root.val)
  {
   if (root.left == null) root.left = new TreeNode(val);
   else _InsertIntoBST(root.left, val);
  }
  else
  {
   if (root.right == null) root.right = new TreeNode(val);
   else _InsertIntoBST(root.right, val);
  }
 }
}

Comments

  1. Not sure why this problem is marked as "Medium", but I liked it :) Since the recursive solution is trivial:

    class Solution {
    public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
    if (root == nullptr) return new TreeNode(val);
    if (val < root->val) {
    root->left = insertIntoBST(root->left, val);
    } else {
    root->right = insertIntoBST(root->right, val);
    }
    return root;
    }
    };

    https://gist.github.com/ttsugriy/4a24bdd0efd1957e5211d329fb7951e2

    I decided to also write a non-recursive solution:

    class Solution {
    public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
    if (root == nullptr) return new TreeNode(val);
    TreeNode* prev = nullptr;
    for (auto node = root; node != nullptr; ) {
    prev = node;
    node = val < node->val ? node->left : node->right;
    }
    auto destination = val < prev->val ? &prev->left : &prev->right;
    *destination = new TreeNode(val);
    return root;
    }
    };

    https://gist.github.com/ttsugriy/85c92ac323f560faea8d3f1d53cf1413

    Thanks for sharing, Boris!

    ReplyDelete

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons