| | 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.SearchInBinarySearchTree; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class SearchInBinarySearchTreeDepthFirstSearchStack : ISearchInBinarySearchTree |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) for a skewed tree, O(log n) for a balanced tree |
| | 21 | | /// Space complexity - O(n) for a skewed tree, O(log n) for a balanced tree |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <param name="val"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public TreeNode? SearchBST(TreeNode? root, int val) |
| 2 | 27 | | { |
| 2 | 28 | | if (root == null) |
| 0 | 29 | | { |
| 0 | 30 | | return null; |
| | 31 | | } |
| | 32 | |
|
| 2 | 33 | | var stack = new Stack<TreeNode>(); |
| | 34 | |
|
| 2 | 35 | | stack.Push(root); |
| | 36 | |
|
| 5 | 37 | | while (stack.Count > 0) |
| 4 | 38 | | { |
| 4 | 39 | | var node = stack.Pop(); |
| | 40 | |
|
| 4 | 41 | | if (node.val == val) |
| 1 | 42 | | { |
| 1 | 43 | | return node; |
| | 44 | | } |
| | 45 | |
|
| 3 | 46 | | if (node.val < val) |
| 1 | 47 | | { |
| 1 | 48 | | if (node.right != null) |
| 1 | 49 | | { |
| 1 | 50 | | stack.Push(node.right); |
| 1 | 51 | | } |
| 1 | 52 | | } |
| | 53 | | else |
| 2 | 54 | | { |
| 2 | 55 | | if (node.left != null) |
| 1 | 56 | | { |
| 1 | 57 | | stack.Push(node.left); |
| 1 | 58 | | } |
| 2 | 59 | | } |
| 3 | 60 | | } |
| | 61 | |
|
| 1 | 62 | | return null; |
| 2 | 63 | | } |
| | 64 | | } |