[LeetCode][JavaScript]Lowest Common Ancestor of a Binary Tree

寻找二叉树中两个节点的最近公共祖先
本文详细阐述了如何在一个给定的二叉树中找到两个指定节点的最近公共祖先,并通过示例代码加以说明。

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

 

 

 


 

 

比较难以描述...

我的理解是把目标的节点向上"冒泡",拿这个做例子:the lowest common ancestor (LCA) of nodes 5 and 1 is 3

从下往上看,6这个节点往上一层返回null,因为这个节点本身,它的左子树和右子树都不包含1和5。

同理7,4,2返回null,

5这个节点左右子树不包含1和5,但它自身是5,返回5,

同理以1为根节点的树返回1,

以1为根节点的树发现左右都不为null,说明找到了。

以上是一种情况,还有一种情况就是一旦发现目前的节点等于p或者q,就可以直接返回,因为默认输入是正确的。

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

 

转载于:https://www.cnblogs.com/Liok3187/p/4644132.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值