一、题目内容

image.png

二、题解

解法1:

思路

image.png

代码

  1. class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. if (root == null || root == p || root == q) {
  4. return root;
  5. }
  6. TreeNode left = lowestCommonAncestor(root.left, p, q);
  7. TreeNode right = lowestCommonAncestor(root.right, p, q);
  8. //p、q都不存在于当前子树
  9. if (left == null && right == null) {
  10. return null;
  11. }
  12. //p、q存在于右子树中
  13. if (left == null) {
  14. return right;
  15. }
  16. //p、q存在于左子树中
  17. if (right == null) {
  18. return left;
  19. }
  20. //p、q在root左右两侧,root为最近公共祖先
  21. return root;
  22. }
  23. }