【LeetCode 0236】【递归】求二叉树的最近公共祖先

  1. Lowest Common Ancestor of a Binary Tree

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, 10^5].
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique.
  • p != q
  • p and q will exist in the tree.
Idea
递归思路:
* 如果当前节点为空或者与p,q任意之一相等,则说明当前节点为p,q最近公共祖先
* 否则分别再在左子树和右子树查找p,q
** 如果左子树 和 右子树 同时找到p,q,则说明当前节点为p,q公共节点
** 如果只是左子树找到,则说明找到的节点为p,q公共最近祖先
** 如果只是右子树找到,则说明找到的节点为p,q公共最近祖先
JavaScript Solution
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    if(!root || root == p || q == root ){
        return root
    }
    let left = lowestCommonAncestor(root.left, p, q)
    let right = lowestCommonAncestor(root.right, p, q)
    return !left ? right : !right ? left : root
};

相关推荐

  1. 经典LeetCode 236. 最近公共祖先

    2024-07-11 05:02:06       51 阅读
  2. LeetCode236.最近公共祖先

    2024-07-11 05:02:06       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 05:02:06       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 05:02:06       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 05:02:06       58 阅读
  4. Python语言-面向对象

    2024-07-11 05:02:06       69 阅读

热门阅读

  1. mysql索引优化

    2024-07-11 05:02:06       18 阅读
  2. Qt 实战(2)搭建开发环境 | 2.2、.pro文件详解

    2024-07-11 05:02:06       20 阅读
  3. 完善kobj_type结构体

    2024-07-11 05:02:06       21 阅读
  4. 【C++中resize和reserve的区别】

    2024-07-11 05:02:06       22 阅读
  5. 音频基础知识

    2024-07-11 05:02:06       24 阅读
  6. SQL 索引

    2024-07-11 05:02:06       20 阅读
  7. docker自定义镜像

    2024-07-11 05:02:06       19 阅读
  8. IDEA Plugins 网络异常解决办法

    2024-07-11 05:02:06       17 阅读
  9. python3记录拨号光纤公网IP

    2024-07-11 05:02:06       19 阅读