leetcode二叉树最近公共祖先236
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
如果当前的节点是p,或者q,则当前节点就是最近的最先节点
递归遍历,判断左节点和右节点是否是要找的节点,返回要找的节点
var lowestCommonAncestor = function(root, p, q) { if(root == null || root == p || root == q) return root let Ltree = lowestCommonAncestor(root.left,p,q) let Rtree = lowestCommonAncestor(root.right,p,q) return Ltree && Rtree ? root : (Ltree || Rtree ? Ltree : Rtree) // if(Ltree == null) return Rtree // if(Rtree == null) return Ltree // return root };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步