Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Analysis

  • Similar to Lowest common ancestor of a binary search tree, have binary tree now instead of binary search tree.
  • 函数定义:如果root下面没有p或者q,返回null;如果两个都有,返回common ancestor;如果只有一个,返回那一个node。

具体:

  • 如果p,q都在root的左边,left指向common ancestor,right指向null,return left
  • 如果p,q都在root的右边,left指向null,right指向common ancestor,return right
  • 如果p,q在root的两边,left指向p, right指向q, return root
  • 注意base condition!
left right return
res null left
null res right
p q root

Code

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    return left == null ? right : right == null ? left : root;
}

Reference

Leetcode