来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

描述

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

说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。

题解

递归版

根据临界条件,实际上可以发现这道题已经被简化为查找以root为根结点的树上是否有p结点或者q结点,如果有就返回p结点或q结点,否则返回null。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  12. if ((root == null) || (root == p) || (root == q)) {
  13. return root;
  14. }
  15. TreeNode left = lowestCommonAncestor(root.left, p, q);
  16. TreeNode right = lowestCommonAncestor(root.right, p, q);
  17. if ((left != null) && (right != null)) {
  18. return root;
  19. }
  20. return (left != null) ? left : right;
  21. }
  22. }

参考

https://blog.csdn.net/qq_28114615/article/details/85715017