|
| 1 | +<p>Given two nodes of a binary tree <code>p</code> and <code>q</code>, return <em>their lowest common ancestor (LCA)</em>.</p> |
| 2 | + |
| 3 | +<p>Each node will have a reference to its parent node. The definition for <code>Node</code> is below:</p> |
| 4 | + |
| 5 | +<pre> |
| 6 | +class Node { |
| 7 | + public int val; |
| 8 | + public Node left; |
| 9 | + public Node right; |
| 10 | + public Node parent; |
| 11 | +} |
| 12 | +</pre> |
| 13 | + |
| 14 | +<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 p and q in a tree T is the lowest node that has both p and q as descendants (where we allow <b>a node to be a descendant of itself</b>)."</p> |
| 15 | + |
| 16 | +<p> </p> |
| 17 | +<p><strong class="example">Example 1:</strong></p> |
| 18 | +<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" style="width: 200px; height: 190px;" /> |
| 19 | +<pre> |
| 20 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 |
| 21 | +<strong>Output:</strong> 3 |
| 22 | +<strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3. |
| 23 | +</pre> |
| 24 | + |
| 25 | +<p><strong class="example">Example 2:</strong></p> |
| 26 | +<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" style="width: 200px; height: 190px;" /> |
| 27 | +<pre> |
| 28 | +<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
| 29 | +<strong>Output:</strong> 5 |
| 30 | +<strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p><strong class="example">Example 3:</strong></p> |
| 34 | + |
| 35 | +<pre> |
| 36 | +<strong>Input:</strong> root = [1,2], p = 1, q = 2 |
| 37 | +<strong>Output:</strong> 1 |
| 38 | +</pre> |
| 39 | + |
| 40 | +<p> </p> |
| 41 | +<p><strong>Constraints:</strong></p> |
| 42 | + |
| 43 | +<ul> |
| 44 | + <li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li> |
| 45 | + <li><code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code></li> |
| 46 | + <li>All <code>Node.val</code> are <strong>unique</strong>.</li> |
| 47 | + <li><code>p != q</code></li> |
| 48 | + <li><code>p</code> and <code>q</code> exist in the tree.</li> |
| 49 | +</ul> |
0 commit comments