1. 程式人生 > >JavaScript刷LeetCode -- 236. Lowest Common Ancestor of a Binary Tree

JavaScript刷LeetCode -- 236. Lowest Common Ancestor of a Binary Tree

一、題目

  Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

  According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

二、題目大意

  找出兩個節點的最低公共祖先節點,允許這兩個節點自身為公共祖先節點。

三、解題思路

  對於這個問題只有兩種情況:

  • 當這兩個節點處於不同的左右子樹中時,那麼最低公共祖先節點就是這兩棵左右子樹的根節點;
  • 當這兩個節點處於同一子樹中,那麼最低公共祖先節點就是這兩個節點中最低的那個節點。

四、程式碼實現

const lowestCommonAncestor = (root, p, q) => {
  if (!root || root == p || root == q) {
    return root
  }
  const left = lowestCommonAncestor(root.left, p, q)
  const right = lowestCommonAncestor(root.right, p, q)

  if (left && right) {
    return root
  }
  return left ? left : right
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。