[Algorithm] Tree: Lowest Common Ancestor
By given a tree structure, task is to find lowest common ancestor:
For example, LCA(4, 5) --> >3
LCA(4,2) --> 1
LCA(3, 5) --> 3
LCA(6, 6) --> 6
Solution to solve the problem:
Found two path to the given two node, then compare two list to see from which point, they are no long equals:
1 2 3 4 | [4,3,1] [5,6,3,1] // the lowest common ancestor would be 3 |
Code:
function createNode(val, left = null, right = null) { return { val, left, addLeft(leftKey) { return (this.left = leftKey ? createNode(leftKey) : null); }, right, addRight(rightKey) { return (this.right = rightKey ? createNode(rightKey) : null); } }; } function createBT(rootKey) { const root = createNode(rootKey); return { root, // Lowest Common Ancestor lca(root, j, k) { function helper(node, val) { let leftPath; let rightPath; if (!node) { return null; } // One we found the value, // constucte an array, then the path will be added to this array // thinking JS call stack, from bottom up // The way recusive works is found the base case, then do the bottom up if (node.val === val) { return [val]; } if (node.left) { // If foudd will return an array // If not then will return null leftPath = helper(node.left, val); if (leftPath !== null) { leftPath.push(node.val); return leftPath; } } if (node.right) { // If foudd will return an array // If not then will return null rightPath = helper(node.right, val); if (rightPath !== null) { rightPath.push(node.val); return rightPath; } } return null; } const jPath = helper(root, j); const kPath = helper(root, k); let found = null; while (jPath.length > 0 && kPath.length > 0) { let fromJ = jPath.pop(); let fromK = kPath.pop(); if (fromJ === fromK) { found = fromJ; } else { break; } } return found; } }; } const tree = createBT("1"); const root = tree.root; const left = root.addLeft("3"); root.addRight("2"); const leftleft = left.addLeft("4"); const leftright = left.addRight("6"); const leftRighttleft = leftright.addLeft("5"); console.log(tree.lca(root, "6", "6")); // 6 console.log(tree.lca(root, "4", "5")); // 3 console.log(tree.lca(root, "4", "2")); // 1 console.log(tree.lca(root, "3", "4")); // 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-03-12 [HTML 5] More about ARIA Relationships
2018-03-12 [HTML5] aria-label & aria-labelledby
2018-03-12 [HTML5] Why ARIA?
2018-03-12 [React] How to use a setState Updater Function with a Reducer Pattern
2017-03-12 [Recompose] When nesting affects Style
2016-03-12 [RxJS] Refactoring CombineLatest to WithLatestFrom