LCA III

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. Returnnullif LCA does not exist.

Example

For the following binary tree:

  4
 / \
3   7
   / \
  5   6

LCA(3, 5) =4

LCA(5, 6) =7

LCA(6, 7) =7

node A or node B may not exist in tree.

Note

需要ResultType来记录a存不存在,b存不存在。

boolean a_exist = left_rt.a_exist || right_rt.a_exist || A == root;

    boolean b\_exist = left\_rt.b\_exist \|\| right\_rt.b\_exist \|\| B == root;

结果要求左右都存在

Code

Last updated