BST insert

by Alex Myronov

JavaScript

function Node(val) {
	this.val = val
	this.left = null
  this.right = null
}

const inorder = (root) => {
	if (!root) return null

  inorder(root.left)
  console.log(root.val)
  inorder(root.right)
}

const insertEl = (root, val) => {
	if (!root) {
  	return new Node(val)
  }
  if (root.val < val) {
  	root.right = insertEl(root.right, val)
  } else {
  	root.left = insertEl(root.left, val)
  }
  return root
}

const insertRecur = (root, val) => {
	if (val > root.val) {
  	if (root.right) {
    	return insert(root.right, val)
    }
    root.right = new Node(val)
    return root.right
  }
  if (root.left) {
  	return insert(root.left, val)
  }
  root.left = new Node(val)
  return root.left
}

const insert = (root, val) => {
	if (!root) return root

	let curr = root
  let parent = root
	
  while (curr) {
  	parent = curr
  	if	(curr.val < val) {
    	curr = curr.right
    } else {
    	curr = curr.left
    }
  }
  
  if (parent.val < val) {
  	parent.right = new Node(val)
    return parent.right
  } else if (parent.val > val) {
  	parent.left = new Node(val)
    return parent.left
  }
  return parent
}

const root = new Node(15)
insert(root, 10)
insert(root, 20)
insert(root, 8)
insert(root, 12)
insert(root, 16)
insert(root, 25)

inorder(root)