一、题目
力扣原题:https://leetcode-cn.com/problemset/all/?listId=ex0k24j
类似题目:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
二叉搜索树是特殊的二叉树,因此二叉树查找“最近公共祖先”的方法同样适用于二叉搜索树,https://blog.csdn.net/sinat_34596644/article/details/106029076。本文只针对二叉搜索树更巧妙的处理方式展开讨论。
二、递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 都在左子树
if (p.val < root.val && q.val < root.val) {