程序员的资源宝库

网站首页 > gitee 正文

[LeetCode] 236. Lowest Common Ancestor of a Binary Tree

sanyeah 2024-03-29 17:58:39 gitee 9 ℃ 0 评论

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3:
Input: root = [1,2], p = 1, q = 2
Output: 1

Constraints:
The number of nodes in the tree is in the range [2, 105].
-109 <= Node.val <= 109
All Node.val are unique.
p != q
p and q will exist in the tree.

二叉树的最近公共祖先。

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

题目跟235题很接近,唯一的不同是235题是一个二叉搜索树(BST),本题是一个二叉树。本题只能用递归做,无法用 BST 的性质判断 p 和 q 到底是在左子树还是在右子树。这道题很考验对递归的理解,以及子节点往父节点返回信息的理解。我参考了这个帖子。

  • 如果我们遇到的是 p 或 q 其中的一个,我们往上一层返回 p 或 q,这样我告诉我的父节点在我这里有其中一个目标值,否则我只能返回 null
  • 在某个节点,如果他的左右孩子都不为空,那么说明这个节点就是要找的最小公共祖先
  • 如果在某个节点他的左右孩子其中有一个为 null,往上返回不为空的那个,这样我可以告诉我的父节点,在我这里有其中一个目标值

分享一个动图理解递归的过程。

复杂度

时间O(n) - 最坏情况会遍历树中所有的 node
空间O(h) - 树的高度

代码

Java实现

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // 如果遍历过程中遇到了p或者q,就往上返回这个节点,否则就往上一层返回null
        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 && right != null) {
            return root;
        }
        // 如果只找到一个孩子,需要给父节点返回另一个不为空的孩子
        return left == null ? right : left;
    }
}

JavaScript实现

/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
    if (root == null || root == p || root == q) return root;
    let left = lowestCommonAncestor(root.left, p, q);
    let right = lowestCommonAncestor(root.right, p, q);
    if (left !== null && right !== null) {
        return root;
    }
    return left == null ? right : left;
};

相关题目

235. Lowest Common Ancestor of a Binary Search Tree
236. Lowest Common Ancestor of a Binary Tree
865. Smallest Subtree with all the Deepest Nodes
1257. Smallest Common Region
1650. Lowest Common Ancestor of a Binary Tree III

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表