Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Tree problems in depth

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Tree problems in depth

Lowest Common Ancestor of a Binary Tree

advancedlayer I2 · Tree problems in depth5 tests

Given the root of a binary tree and two nodes p and q from it, return their lowest common ancestor: the deepest node that has both of them somewhere below it.

  • A node counts as an ancestor of itself, so the answer may be p or q
  • p and q are node objects, not values, and both are present in the tree
  • This is an ordinary binary tree — no ordering to exploit
  • find(root, val) is provided so you can fetch a node by value

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen