LeetCode236:
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

  1. class Solution {
  2. boolean flag = false;
  3. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  4. find(root.left, p);
  5. boolean l1 = flag;
  6. flag = false;
  7. find(root.left, q);
  8. boolean l2 = flag;
  9. flag = false;
  10. find(root.right, p);
  11. boolean r1 = flag;
  12. flag = false;
  13. find(root.right, q);
  14. boolean r2 = flag;
  15. flag = false;
  16. if (l1 && l2) {
  17. return lowestCommonAncestor(root.left, p, q);
  18. } else if (r1 && r2) {
  19. return lowestCommonAncestor(root.right, p, q);
  20. } else {
  21. return root;
  22. }
  23. }
  24. private void find(TreeNode left, TreeNode p) {
  25. if (left == null){
  26. return;
  27. }
  28. if (left.val == p.val) {
  29. flag = true;
  30. return;
  31. }
  32. if (left.left != null) {
  33. find(left.left, p);
  34. }
  35. if (left.right != null) {
  36. find(left.right, p);
  37. }
  38. }
  39. }

代码随想录的解法

  1. class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. return lowestCommonAncestor1(root, p, q);
  4. }
  5. //这个函数不仅仅充当了寻找最近公共祖先的功能。
  6. //也充当了寻找某个值的功能。
  7. public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
  8. if (root == null || root == p || root == q) {
  9. return root;
  10. }
  11. TreeNode left = lowestCommonAncestor1(root.left, p, q);
  12. TreeNode right = lowestCommonAncestor1(root.right, p, q);
  13. if (left != null && right != null) {// 左右子树分别找到了,说明此时的root就是要求的结果
  14. return root;
  15. }
  16. if (left == null) {
  17. return right;
  18. }
  19. return left;
  20. }
  21. }

参考文献

  1. 「代码随想录」带你学透二叉树!236. 二叉树的最近公共祖先:【递归与回溯】详解