package com.fishercoder.solutions;

import com.fishercoder.common.classes.TreeNode;

/**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.*/
public class _236 {

    /**We need to find TWO nodes in the tree, so we'll have to divide and conquer this tree, we need to have two nodes to as the intermediate
    result, inspired by this one: https://discuss.leetcode.com/topic/18566/my-java-solution-which-is-easy-to-understand
    Also, refer to my earlier drawings:http://www.fishercoder.com/2016/06/23/lowest-common-ancestor-of-a-binary-tree/
    I'm really impressed with myself at that time!*/
    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);
        if(left != null && right != null) return root;
        return left != null ? left : right;
    }

}

@@ -81,16 +81,68 @@
 de;%0A%0A/**
+%0A * 236. Lowest Common Ancestor of a Binary Tree%0A * 
 Given a 
@@ -224,17 +224,18 @@
 e tree.%0A
-%0A
+ *
  Accordi
@@ -275,16 +275,19 @@
 kipedia:
+%0A *
  %E2%80%9CThe lo
@@ -367,16 +367,19 @@
 ode in T
+%0A *
  that ha
@@ -617,16 +617,17 @@
 %0A 7   4%0A
+%0A
  For exa
@@ -687,16 +687,17 @@
  1 is 3.
+%0A
  Another
@@ -813,16 +813,17 @@
 tion.*/%0A
+%0A
 public c
@@ -880,16 +880,23 @@
 he tree,
+%0A     *
  so we'l
@@ -934,16 +934,23 @@
 is tree,
+%0A     *
  we need
@@ -994,20 +994,16 @@
 iate
-%0A   
  result,
  ins
@@ -1002,122 +1002,17 @@
 ult,
- inspired by this one: https://discuss.leetcode.com/topic/18566/my-java-solution-which-is-easy-to-understand%0A    A
+%0A     * a
 lso,
@@ -1123,16 +1123,19 @@
 ree/%0A   
+  *
  I'm rea
@@ -1176,16 +1176,17 @@
 time!*/%0A
+%0A
     publ
@@ -1269,16 +1269,17 @@
       if
+ 
 (root ==
@@ -1462,16 +1462,17 @@
       if
+ 
 (left !=

edit 236