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
};
原文地址:https://www.cnblogs.com/jiaobaba/p/14347112.html