578.Lowest Common Ancestor III

https://www.lintcode.com/problem/578/

1.Description(Medium)

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.Return

nullif LCA does not exist. (this is what diff with Leetcode 236)

node A or node B may not exist in tree. Each node has a different value

Example1

For the following binary tree:

  4
 / \
3   7
   / \
  5   6

LCA(3, 5) =4

LCA(5, 6) =7

LCA(6, 7) =7

Example2

Input: 
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7 
5 8
Output: 
4
7
7
null
Explanation:
  4
 / \
3   7
   / \
  5   6

LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null

Example3

2.Code

https://www.jiuzhang.com/problem/lowest-common-ancestor-iii/

Solution 1: 加一个helper class 来track节点A和B是否存在

Solution 2:

Divide & Conquer + Global Variable(不需要 ResultType)

这题和 LCA 原题的区别主要是要找的 A 和 B 可能并不存在树里。所以我们要做出这两个改变

  1. 用全局变量把 A 和 B 是否找到保存起来。最后在 main function 里面要查看是否都找到

  2. 当 root 等于 A 或者 B 时不能直接返回root了。原题可以直接返回是因为两个 node 是保证存在的所以这情况下 LCA 一定是 root。

  3. 现在 root 等于 A 或者 B 我们还是要继续往下找是否存在另外的一个

不用 ResultType 的一个好处是:如果面试的时候出了一个原题,然后问这题做 follow up。如果从头开始写 result type 代码改动会比较大。一是比较容易写错,二是时间可能会不够。

这个方法只需要增加两个全局变量并且改动 LCA 原题的代码两行即可。

Last updated

Was this helpful?