1、前言
![](https://img.haomeiwen.com/i11345146/5a0ff43419edd24a.png)
2、思路
父节点可能在左边、右边、或者共同的父。
3、代码
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);
if(left != null && right != null){
return root;
}
return left == null ? right : left;
}
}
网友评论