首页 > 其他 > 详细

leetcode二叉树最近公共祖先236

时间:2021-01-29 23:38:38      阅读:26      评论:0      收藏:0      [点我收藏+]

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

技术分享图片

如果当前的节点是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
};

 

leetcode二叉树最近公共祖先236

原文:https://www.cnblogs.com/jiaobaba/p/14347112.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!