import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param p int整型
     * @param q int整型
     * @return int整型
     */
    public int result = Integer.MAX_VALUE;
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        if (root == null) {
            return result;
        }
        // 如果节点本身就是祖先节点
        if (root.val == p || root.val == q) {
            return root.val;
        }
        // 递归左右子树,寻找公共祖先
        int left = lowestCommonAncestor(root.left, p, q);
        int right = lowestCommonAncestor(root.right, p, q);
        // 如果left==result说明左子树找不到,因为root == null 才返回result
        if (left == result) {
            return right;
        }
        // 右子树找不到就返回左子树
        if (right == result) {
            return left;
        }
        return root.val;
    }
}

本题知识点分析:

1.递归

2.二叉树

3.数学模拟

本题解题思路分析:

1.递归寻找两个子节点的最近公共祖先

2.如果root==null,返回result,作为没有找到的标识

3.如果当前节点值就等于p或者q,直接返回当前节点

4.分别递归左右子树,根据result标识符进行判断

本题使用编程语言: Java