code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

235 Lowest Common Ancestor Of A Binary Search Tree

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

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

const lowestCommonAncestorOfABinarySearchTree = (root, p, q) => {
  if (p.val < root.val && q.val < root.val) return lowestCommonAncestorOfABinarySearchTree(root.left, p, q)
  else if (p.val > root.val && q.val > root.val) return lowestCommonAncestorOfABinarySearchTree(root.right, p, q)
  else return root
}

test('lowestCommonAncestorOfABinarySearchTree', () => {
  const t1 = new TreeNode(6)
  t1.left = new TreeNode(2)
  t1.right = new TreeNode(8)
  t1.left.left = new TreeNode(0)
  t1.left.right = new TreeNode(4)
  t1.left.right.left = new TreeNode(3)
  t1.left.right.right = new TreeNode(5)
  t1.right.left = new TreeNode(7)
  t1.right.right = new TreeNode(9)
  console.log(lowestCommonAncestorOfABinarySearchTree(t1, new TreeNode(2), new TreeNode(8)))
})

Created 2021-01-31T07:09:19+05:18, updated 2021-01-31T07:30:41+05:18 · History · Edit