题目描述
// 236. 二叉树的最近公共祖先
// 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
// 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖
// 先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可
// 以是它自己的祖先)。”
复制代码
题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 本题和【剑指offer】68.2 二叉树的最近公共祖先 一模一样
// 看到https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/
// 图文并茂写得很好,不理解可以看看。
//
// 执行用时:7 ms, 在所有 Java 提交中击败了99.93%的用户
// 内存消耗:40.6 MB, 在所有 Java 提交中击败了55.10%的用户
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q)
return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null)
return right;
else if (right == null)
return left;
return root;
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END