题目:
  
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。

可以使用递归的方式来解决这个问题。递归函数的基本思路是:
- 如果当前节点为空,返回null
- 如果当前节点就是其中一个目标节点,返回当前节点
- 分别在左子树和右子树中查找目标节点
- 如果左右子树都找到了目标节点,说明当前节点就是最近公共祖先,返回当前节点
- 如果只在左子树找到了一个目标节点,返回左子树的结果
- 如果只在右子树找到了一个目标节点,返回右子树的结果
  这个leetcode官方题解下面的树很正确的具象化了这个题的任务。
这个leetcode官方题解下面的树很正确的具象化了这个题的任务。
下面附上代码:
  
public class no_236 {
    public static void main(String[] args) {
        Integer[] input = {3, 5, 1, 6, 2, 0, 8, null, null, 7, 4};
        TreeNode root = TreeNode.buildTree(input);
        int p = 5, q = 1;
        TreeNode treeNode = lowestCommonAncestor(root, root.left, root.right);
        System.out.println(treeNode.val);
    }
    public static 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;
        }
        if (left != null) {
            return left;
        }
        if (right != null) {
            return right;
        }
        return null;
    }
}













![BUUCTF [GUET-CTF2019]zips 1](https://img-blog.csdnimg.cn/img_convert/b294954725b8b05cc6bf840c4bd36115.png)





