题目链接
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;
}
}