一、题目内容

image.png

二、题解

解法1:

思路

后续遍历,判断左右节点与根的关系

代码

  1. public class Solution {
  2. //后续遍历,判断左右节点与根的关系
  3. public int lowestCommonAncestor(TreeNode root, int o1, int o2) {
  4. TreeNode p = new TreeNode(o1);
  5. TreeNode q = new TreeNode(o2);
  6. TreeNode res = ancestor(root, p, q);
  7. return res == null ? -1 : res.val;
  8. }
  9. //后续遍历,判断左右节点与根的关系
  10. private TreeNode ancestor(TreeNode root, TreeNode p, TreeNode q) {
  11. if (root == null || root.val == p.val || root.val == q.val) {
  12. return root;
  13. }
  14. TreeNode left = ancestor(root.left, p, q);
  15. TreeNode right = ancestor(root.right, p, q);
  16. //p、q都不存在于当前子树
  17. if (left == null && right == null) {
  18. return null;
  19. }
  20. //p、q存在于左子树中
  21. if (right == null) {
  22. return left;
  23. }
  24. //p、q存在于右子树中
  25. if (left == null) {
  26. return right;
  27. }
  28. //p、q在root左右两侧,root为最近公共祖先
  29. return root; // (都非空)
  30. }
  31. }