# Lowest Common Ancestor III

&#x20;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 `null` if LCA does not exist.

```java
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: The root of the binary tree.
     * @param A: A TreeNode
     * @param B: A TreeNode
     * @return: Return the LCA of the two nodes.
     */
     
    public boolean foundA = false, foundB = false;
    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
        // write your code here
        TreeNode res = helper(root,A,B);
        
        if(foundA && foundB){
            return res;
        }else{
            return null;
        }
        
    }
   
    public TreeNode helper(TreeNode root, TreeNode A, TreeNode B){
        if(root == null){
            return root;
        }
        
        //先分派 再检查 不然结果会出错
        TreeNode left = helper(root.left,A,B);
        TreeNode right = helper(root.right,A,B);
        if(root == A|| root == B){
            //如果不或foundA， 当找到A后 遍历别的点时，如果root != //A，将会改变foundA的值
        
            foundA = (root == A )|| foundA; 
            foundB = (root == B) ||foundB;
            
            return root;
        }
        

        
        if(left != null && right != null){
            return root;
        }
        
        else if(left != null){
            return left;
        }
        else if(right != null){
            return right;
        }
        
        return null;
    }
    
    
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shuati.gitbook.io/crack-lintcode/binary-tree/lowest-common-ancestor-iii-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
