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
};
复制代码

 

posted @   张最棒  阅读(48)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示