Solution 1BST Recursive

  • TimeO(h), where h is the height of the tree
  • SpaceO(1), since we are not using any extra space

where, h is log(n) in a balanced tree, and n is the number of nodes in the tree.

This is a Binary Search Tree, so we can use the properties of BST to find the LCA.
In a BST, left child nodes are less than the parent node, and right child nodes are greater than the parent node.
Traditionally, nodes have unique values in a BST.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        '''
        Time Complexity: O(h), where h is the height of the tree.
        Space Complexity: O(1), since we are not using any extra space.
        where, h is log(n) in a balanced tree, and n is the number of nodes in the tree.

        This is a Binary Search Tree, so we can use the properties of BST to find the LCA.
        In a BST, left child nodes are less than the parent node, and right child nodes are greater than the parent node.
        Traditionally, nodes have unique values in a BST.
        '''
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        if p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)
        return root
Leet Code/python.py · L1654–1676
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root.val > p.val && root.val > q.val) {
        return lowestCommonAncestor(root.left, p, q);
    }
    if (root.val < p.val && root.val < q.val) {
        return lowestCommonAncestor(root.right, p, q);
    }
    return root;
}
Leet Code/java.java · L1119–1137