【DFS】LeetCode 235. 二叉搜索树的最近公共祖先
题目链接
思路
与 【DFS】LeetCode 236. 二叉树的最近公共祖先 一模一样
代码
class Solution {
public 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);
// p and q are not in left subtree
if(left == null){
return right;
}
// p and q are not in right subtree
if(right == null){
return left;
}
// p and q are in the left subtree and right subtree respectively
return root;
}
}