|
| 1 | +<p>Given the <code>root</code> of a binary tree, return <em>the lowest common ancestor (LCA) of two given nodes, </em><code>p</code><em> and </em><code>q</code>. If either node <code>p</code> or <code>q</code> <strong>does not exist</strong> in the tree, return <code>null</code>. All values of the nodes in the tree are <strong>unique</strong>.</p> |
| 2 | + |
| 3 | +<p>According to 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 two nodes <code>p</code> and <code>q</code> in a binary tree <code>T</code> is the lowest node that has both <code>p</code> and <code>q</code> as <strong>descendants</strong> (where we allow <b>a node to be a descendant of itself</b>)". 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], p = 5, q = 1 |
| 10 | +<strong>Output:</strong> 3 |
| 11 | +<strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3.</pre> |
| 12 | + |
| 13 | +<p><strong class="example">Example 2:</strong></p> |
| 14 | + |
| 15 | +<p><img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" /></p> |
| 16 | + |
| 17 | +<pre> |
| 18 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
| 19 | +<strong>Output:</strong> 5 |
| 20 | +<strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5. A node can be a descendant of itself according to the definition of LCA.</pre> |
| 21 | + |
| 22 | +<p><strong class="example">Example 3:</strong></p> |
| 23 | + |
| 24 | +<p><img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" /></p> |
| 25 | + |
| 26 | +<pre> |
| 27 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10 |
| 28 | +<strong>Output:</strong> null |
| 29 | +<strong>Explanation:</strong> Node 10 does not exist in the tree, so return null. |
| 30 | +</pre> |
| 31 | + |
| 32 | +<p> </p> |
| 33 | +<p><strong>Constraints:</strong></p> |
| 34 | + |
| 35 | +<ul> |
| 36 | + <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> |
| 37 | + <li><code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code></li> |
| 38 | + <li>All <code>Node.val</code> are <strong>unique</strong>.</li> |
| 39 | + <li><code>p != q</code></li> |
| 40 | +</ul> |
| 41 | + |
| 42 | +<p> </p> |
| 43 | +<strong>Follow up:</strong> Can you find the LCA traversing the tree, without checking nodes existence? |
0 commit comments