Lowest Common Ancestor II

update Aug 27, 2017 22:06

LintCodearrow-up-right

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

The node has an extra attribute parent which point to the father of itself. The root's parent is null.

Example

  For the following binary tree:

    4
   / \
  3   7
     / \
    5   6
  LCA(3, 5) = 4

  LCA(5, 6) = 7

  LCA(6, 7) = 7

Basic Idea:

由于这道题的二叉树给了父节点,我们可以从A,B开始往上直到root,分别得到两个链表,如果A,B的公共节点存在,那么就相当于两个链表有共同部分(链表分叉)。此时我们只要从root开始向下,比较每个同样位置的元素,直到下一个开始分叉位置。

Java Code:

Python Code:

update Dec 20, 2017 1:04

Update

更简单的方法是使用 HashSet,先把第一条链表每个node加入set,然后依次验证第二条链表的node是否在其中,第一个在 set 中的就是分叉节点;

Python Code:

Java Code: