| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.LowestCommonAncestorOfDeepestLeaves; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class LowestCommonAncestorOfDeepestLeavesDepthFirstSearch : ILowestCommonAncestorOfDeepestLeaves |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public TreeNode LcaDeepestLeaves(TreeNode root) |
| 3 | 26 | | { |
| 3 | 27 | | return FindLcaDeepestLeaves(root).TreeNode!; |
| 3 | 28 | | } |
| | 29 | |
|
| | 30 | | private static (TreeNode? TreeNode, int Depth) FindLcaDeepestLeaves(TreeNode? root) |
| 31 | 31 | | { |
| 31 | 32 | | if (root == null) |
| 17 | 33 | | { |
| 17 | 34 | | return (null, 0); |
| | 35 | | } |
| | 36 | |
|
| 14 | 37 | | var left = FindLcaDeepestLeaves(root.left); |
| 14 | 38 | | var right = FindLcaDeepestLeaves(root.right); |
| | 39 | |
|
| 14 | 40 | | if (left.Depth > right.Depth) |
| 2 | 41 | | { |
| 2 | 42 | | return (left.TreeNode, left.Depth + 1); |
| | 43 | | } |
| | 44 | |
|
| 12 | 45 | | return right.Depth > left.Depth ? (right.TreeNode, right.Depth + 1) : (root, left.Depth + 1); |
| 31 | 46 | | } |
| | 47 | | } |