| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.MaximumDepthOfBinaryTree; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class MaximumDepthOfBinaryTreeBreadthFirstSearch : IMaximumDepthOfBinaryTree |
| | | 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 int MaxDepth(TreeNode? root) |
| | 3 | 26 | | { |
| | 3 | 27 | | if (root == null) |
| | 1 | 28 | | { |
| | 1 | 29 | | return 0; |
| | | 30 | | } |
| | | 31 | | |
| | 2 | 32 | | var maxDepth = 0; |
| | | 33 | | |
| | 2 | 34 | | var queue = new Queue<(TreeNode, int)>(); |
| | | 35 | | |
| | 2 | 36 | | queue.Enqueue((root, 1)); |
| | | 37 | | |
| | 9 | 38 | | while (queue.Count > 0) |
| | 7 | 39 | | { |
| | 7 | 40 | | var (treeNode, depth) = queue.Dequeue(); |
| | | 41 | | |
| | 7 | 42 | | if (treeNode.left == null && treeNode.right == null) |
| | 4 | 43 | | { |
| | 4 | 44 | | maxDepth = Math.Max(maxDepth, depth); |
| | 4 | 45 | | } |
| | | 46 | | else |
| | 3 | 47 | | { |
| | 3 | 48 | | depth++; |
| | | 49 | | |
| | 3 | 50 | | if (treeNode.left != null) |
| | 2 | 51 | | { |
| | 2 | 52 | | queue.Enqueue((treeNode.left, depth)); |
| | 2 | 53 | | } |
| | | 54 | | |
| | 3 | 55 | | if (treeNode.right != null) |
| | 3 | 56 | | { |
| | 3 | 57 | | queue.Enqueue((treeNode.right, depth)); |
| | 3 | 58 | | } |
| | 3 | 59 | | } |
| | 7 | 60 | | } |
| | | 61 | | |
| | 2 | 62 | | return maxDepth; |
| | 3 | 63 | | } |
| | | 64 | | } |