栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在二叉树中找到最少的祖先

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在二叉树中找到最少的祖先

从普通的深度优先搜索算法开始:

public Node find(Node node, int target) {    if(node == null || node.value == target) {        return node;    }    if(node.value > target) {        return find(node.left, target);    } else {        return find(node.right, target);    }}

现在,将其修改为采用两个“目标”参数,即target1和target2。

当搜索target1带您离开,而搜索target2带您去时,您已经找到了LCA。

假设两个目标确实存在。如果需要断言它们确实如此,则需要在找到潜在的LCA之后继续搜索。

public Node findLca(Node node, int t1, int t2) {    if(node == null) {        return null;    }    if(node.value > t2 && node.value > t1) {        // both targets are left        return findLca(node.left, t1, t2);    } else if (node.value < t2 && node.value < t1) {        // both targets are right        return findLca(node.right, t1, t2);    } else {        // either we are diverging or both targets are equal        // in both cases so we've found the LCA        // check for actual existence of targets here, if you like        return node;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/454320.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号