Lowest Common Ancestor of BST
Lowest Common Ancestor of a Binary Search Tree
Problem Description
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Intuition
Since tree is BST, we know every left child is strictly less than root value, and every right child is strictly greater. We determine which node is smaller and let it be smaller node, another is larger node. If root is between these two nodes, this node is the lowest common ancestor.
Algorithm
1 | class Solution { |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 YouChen's Blog!