image.png

解题思路

递归

  1. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  2. // LCA 问题
  3. if (root == null) {
  4. return root;
  5. }
  6. if (root == p || root == q) {
  7. return root;
  8. }
  9. TreeNode left = lowestCommonAncestor(root.left, p, q);
  10. TreeNode right = lowestCommonAncestor(root.right, p, q);
  11. if (left != null && right != null) {
  12. return root;
  13. } else if (left != null) {
  14. return left;
  15. } else if (right != null) {
  16. return right;
  17. }
  18. return null;
  19. }