15 Jun 2024C++ / Python / TypeScriptEasy

Lowest Common Ancestor of a Binary Search Tree

Collected C++, Python, TypeScript solutions for lowest common ancestor of a binary search tree. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Lowest Common Ancestor of a Binary Search Tree. the solution files are available below.

solution files

  • C++ lowest-common-ancestor-of-a-binary-search-tree/synced-solution.cpp
  • Python lowest-common-ancestor-of-a-binary-search-tree/synced-solution.py
  • TypeScript lowest-common-ancestor-of-a-binary-search-tree/synced-solution.ts

Solution files

Pythonlowest-common-ancestor-of-a-binary-search-tree/synced-solution.py
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
    while root:
        if p.val < root.val and q.val < root.val:
            root = root.left
        elif p.val > root.val and q.val > root.val:
            root = root.right
        else:
            return root
C++lowest-common-ancestor-of-a-binary-search-tree/synced-solution.cpp
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        while (root) {
            if (p->val < root->val && q->val < root->val) {
                root = root->left;
            } else if (p->val > root->val && q->val > root->val) {
                root = root->right;
            } else {
                return root;
            }
        }
        return nullptr;
    }
};
TypeScriptlowest-common-ancestor-of-a-binary-search-tree/synced-solution.ts
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    while (root) {
        if (p!.val < root.val && q!.val < root.val) {
            root = root.left;
        } else if (p!.val > root.val && q!.val > root.val) {
            root = root.right;
        } else {
            return root;
        }
    }
    return null;
}