https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
由于二叉搜索树是有序的,所以比题236更简单。
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root==p) return p;if(root==q) return q;//p,q都不是root。看p,q在同一侧孩子吗?//看p,q分别在哪一侧if(p.val<root.val&&q.val<root.val){//都在左子树return lowestCommonAncestor(root.left,p,q);}else if(p.val>root.val&&q.val>root.val){//都在右子树return lowestCommonAncestor(root.right,p,q);}else{//分别在左右return root;}}
}
/**
两个节点ab的最近公共祖先 1.他们两的父节点c 2.他们两其中之一a,a是b的父节点*/