首页 > 其他分享 >Lowest Common Ancestor

Lowest Common Ancestor

时间:2024-05-12 16:52:51浏览次数:10  
标签:Lowest right TreeNode Common return Ancestor root 节点 left

Source

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Example
        4

    /     \

  3         7

          /     \

        5         6
For 3 and 5, the LCA is 4.

For 5 and 6, the LCA is 7.
For 6 and 7, the LCA is 7.

题解1 - 自底向上

初次接触这种题可能会没有什么思路,在没有思路的情况下我们就从简单例子开始分析!首先看看3和5,这两个节点分居根节点4的两侧,如果可以从子节点往父节点递推,那么他们将在根节点4处第一次重合;再来看看5和6,这两个都在根节点4的右侧,沿着父节点往上递推,他们将在节点7处第一次重合;最后来看看6和7,此时由于7是6的父节点,故7即为所求。从这三个基本例子我们可以总结出两种思路——自顶向下(从前往后递推)和自底向上(从后往前递推)。

顺着上述实例的分析,我们首先看看自底向上的思路,自底向上的实现用一句话来总结就是——如果遍历到的当前节点是 A/B 中的任意一个,那么我们就向父节点汇报此节点,否则递归到节点为空时返回空值。具体来说会有如下几种情况:

1、当前节点不是两个节点中的任意一个,此时应判断左右子树的返回结果。

  • 若左右子树均返回非空节点,那么当前节点一定是所求的根节点,将当前节点逐层向前汇报。// 两个节点分居树的两侧
  • 若左右子树仅有一个子树返回非空节点,则将此非空节点向父节点汇报。// 节点仅存在于树的一侧
  • 若左右子树均返回NULL, 则向父节点返回NULL. // 节点不在这棵树中

2、当前节点即为两个节点中的一个,此时向父节点返回当前节点。
根据此递归模型容易看出应该使用先序/后序遍历来实现。

C++ Recursion From Bottom to Top

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
        // return either A or B or NULL
        if (NULL == root || root == A || root == B) return root;

        TreeNode *left = lowestCommonAncestor(root->left, A, B);
        TreeNode *right = lowestCommonAncestor(root->right, A, B);

        // A and B are on both sides
        if ((NULL != left) && (NULL != right)) return root;

        // either left or right or NULL
        return (NULL != left) ? left : right;
    }
};

Java

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) return null;

        TreeNode lNode = lowestCommonAncestor(root.left, A, B);
        TreeNode rNode = lowestCommonAncestor(root.right, A, B);
        // root is the LCA of A and B
        if (lNode != null && rNode != null) return root;
        // root node is A/B(including the case below)
        if (root == A || root == B) return root;
        // return lNode/rNode if root is not LCA
        return (lNode != null) ? lNode : rNode;
    }
}

源码分析

结合例子和递归的整体思想去理解代码,在root == A || root == B后即层层上浮(自底向上),直至找到最终的最小公共祖先节点。

最后一行return (NULL != left) ? left : right;将非空的左右子树节点和空值都包含在内了。

关于重复节点:由于这里比较的是元素地址,因此可以认为树中不存在重复元素,否则不符合树的数据结构。

题解 - 自底向上(计数器)

为了解决上述方法可能导致误判的情况,我们可以对返回结果添加计数器来解决。由于此计数器的值只能由子树向上递推,故应该用后序遍历。在类中添加私有变量较为方便。

定义pair<TreeNode *, int> result(node, counter)表示遍历到某节点时的返回结果,返回的node表示LCA 路径中的可能的最小节点,相应的计数器counter则表示目前和A或者B匹配的节点数,若计数器为2,则表示已匹配过两次,该节点即为所求,若只匹配过一次,还需进一步向上递推。表述地可能比较模糊,还是看看代码吧。

C++

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
        if ((NULL == A) || (NULL == B)) return NULL;

        pair<TreeNode *, int> result = helper(root, A, B);

        if (A != B) {
            return (2 == result.second) ? result.first : NULL;
        } else {
            return (1 == result.second) ? result.first : NULL;
        }
    }

private:
    pair<TreeNode *, int> helper(TreeNode *root, TreeNode *A, TreeNode *B) {
        TreeNode * node = NULL;
        if (NULL == root) return make_pair(node, 0);

        pair<TreeNode *, int> left = helper(root->left, A, B);
        pair<TreeNode *, int> right = helper(root->right, A, B);

        // return either A or B
        int count = max(left.second, right.second);
        if (A == root || B == root)  return make_pair(root, ++count);

        // A and B are on both sides
        if (NULL != left.first && NULL != right.first) return make_pair(root, 2);

        // return either left or right or NULL
        return (NULL != left.first) ? left : right;
    }
};

Java

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    private int count = 0;
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
        TreeNode result = helper(root, A, B);
        if (A == B) {
            return result;
        } else {
            return (count == 2) ? result : null;
        }
    }

    private TreeNode helper(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) return null;

        TreeNode lNode = helper(root.left, A, B);
        TreeNode rNode = helper(root.right, A, B);
        // root is the LCA of A and B
        if (lNode != null && rNode != null) return root;
        // root node is A/B(including the case below)
        if (root == A || root == B) {
            count++;
            return root;
        }
        // return lNode/rNode if root is not LCA
        return (lNode != null) ? lNode : rNode;
    }
}

源码分析

在A == B时,计数器返回1的节点即为我们需要的节点,否则只取返回2的节点,如此便保证了该方法的正确性。对这种实现还有问题的在下面评论吧。

 

 

 

标签:Lowest,right,TreeNode,Common,return,Ancestor,root,节点,left
From: https://www.cnblogs.com/lyc94620/p/18187933

相关文章

  • Common-Linux-commands
    Linux常用命令用户切换//切换到超级用户gec@ubuntu:~$sudo-s[sudo]passwordforgec:root@ubuntu:~# //root表示超级用户名字#表示超级用户权限标志//切换到普通用户root@ubuntu:~#suxxx//第一种方式xxx指的是系统中用户......
  • Java开发利器Commons Lang之元组Tuple
    标准Java库没有提供足够的方法来操作其核心类,ApacheCommonsLang提供了这些额外的方法。ApacheCommonsLang为java提供了大量的帮助工具。langAPI,特别是String操作方法、基本数值方法、对象反射、并发、创建和序列化以及System属性。此外,它还包含对java.util.Date的基本增......
  • Apache Commons Collections反序列化漏洞
    目录复现环境准备POC漏洞原理分析构造反射链TransformedMap利用链ApacheCommonsCollections的反序列化漏洞在2015年被曝光,引起了广泛的关注,算是java历史上最出名同时也是最具有代表性的反序列化漏洞。复现环境准备jdk1.7版本下载压缩包链接:https://pan.baidu.com/s/......
  • xhs全参xs,xt,xscommon逆向分析
    声明本文章中所有内容仅供学习交流,抓包内容、敏感网址、数据接口均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除!目标网站aHR0cHM6Ly93d3cueGlhb2hvbmdzaHUuY29tL2V4cGxvcmUvNjYyNDcxYzkwMDAwMDAwMDA0MDE5ZGYwTrace[x......
  • 导入文件报错(common.AssertionFailed at common.Assert.verify)
    common.AssertionFailedatcommon.Assert.verify(UnknownSource)atjxl.read.biff.WorkbookParser.getName(UnknownSource)atjxl.biff.formula.NameRange.read(UnknownSource)atjxl.biff.formula.TokenFormulaParser.g(UnknownSource)atjxl.b......
  • uniapp-common.css
    /*by:https://www.cnblogs.com/zzz7/p/15593167.html*/page{height:100%;width:190%;background-color:#F8F8F8;}.container{height:100%;width:100%;}/*主题色*/.main-color{color:#1bbf80;}.white-color{color:#ffffff;......
  • WPF relativesource,self,FindAncestor,AncestorType,AncestorLevel,PreviousData,Tem
    <Windowx:Class="WpfApp68.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com......
  • commonjs
    Commonjs什么是CommonJsCommonJs是js模块化的社区规范模块化产生的原因随着前端页面复杂度的提升,依赖的第三方库的增加,导致的js依赖混乱,全局变量的污染,和命名冲突单个js文件内容太多,导致了维护困难,拆分成为多个文件又会发生第一点描述的问题v8引擎的出现,让js......
  • org.apache.commons.lang3.ArrayUtils 学习笔记
    1234567891011121314151617181920212223242526272829303132333435package com.nihaorz.model; /** *@作者王睿 *@时间2016-5-17上午10:05:17 * */public class Person{    private Stringid;    pr......
  • LOJ#6020. 「from CommonAnts」寻找 LCT
    linkofproblem。依旧是非常精妙的做法呢!问了神仙lca才知道怎么做了,目前网上是没有题解的,有的只是一份带注释的代码的英文题解。我的细节实现也是看了这份代码得以补足的。我们定义一些量:原树重心为rt,rt的某个儿子叫做son,son子树内的某个节点为x。首先考虑哪些连通块......