|
| 1 | +<p>Given the <code>root</code> of a binary tree and an array of <code>TreeNode</code> objects <code>nodes</code>, return <em>the lowest common ancestor (LCA) of <strong>all the nodes</strong> in </em><code>nodes</code>. All the nodes will exist in the tree, and all values of the tree's nodes are <strong>unique</strong>.</p> |
| 2 | + |
| 3 | +<p>Extending the <strong><a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a></strong>: "The lowest common ancestor of <code>n</code> nodes <code>p<sub>1</sub></code>, <code>p<sub>2</sub></code>, ..., <code>p<sub>n</sub></code> in a binary tree <code>T</code> is the lowest node that has every <code>p<sub>i</sub></code> as a <strong>descendant</strong> (where we allow <b>a node to be a descendant of itself</b>) for every valid <code>i</code>". A <strong>descendant</strong> of a node <code>x</code> is a node <code>y</code> that is on the path from node <code>x</code> to some leaf node.</p> |
| 4 | + |
| 5 | +<p> </p> |
| 6 | +<p><strong class="example">Example 1:</strong></p> |
| 7 | +<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" /> |
| 8 | +<pre> |
| 9 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7] |
| 10 | +<strong>Output:</strong> 2 |
| 11 | +<strong>Explanation:</strong> The lowest common ancestor of nodes 4 and 7 is node 2. |
| 12 | +</pre> |
| 13 | + |
| 14 | +<p><strong class="example">Example 2:</strong></p> |
| 15 | +<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" /> |
| 16 | +<pre> |
| 17 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1] |
| 18 | +<strong>Output:</strong> 1 |
| 19 | +<strong>Explanation:</strong> The lowest common ancestor of a single node is the node itself. |
| 20 | + |
| 21 | +</pre> |
| 22 | + |
| 23 | +<p><strong class="example">Example 3:</strong></p> |
| 24 | +<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" /> |
| 25 | +<pre> |
| 26 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [7,6,2,4] |
| 27 | +<strong>Output:</strong> 5 |
| 28 | +<strong>Explanation:</strong> The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5. |
| 29 | +</pre> |
| 30 | + |
| 31 | +<p> </p> |
| 32 | +<p><strong>Constraints:</strong></p> |
| 33 | + |
| 34 | +<ul> |
| 35 | + <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> |
| 36 | + <li><code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code></li> |
| 37 | + <li>All <code>Node.val</code> are <strong>unique</strong>.</li> |
| 38 | + <li>All <code>nodes[i]</code> will exist in the tree.</li> |
| 39 | + <li>All <code>nodes[i]</code> are distinct.</li> |
| 40 | +</ul> |
0 commit comments