| | 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.FindElementsInContaminatedBinaryTree; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class FindElementsInContaminatedBinaryTreeDepthFirstSearch : IFindElementsInContaminatedBinaryTree |
| | 18 | | { |
| | 19 | | private readonly TreeNode _root; |
| | 20 | |
|
| | 21 | | /// <summary> |
| | 22 | | /// Time complexity - O(1) |
| | 23 | | /// Space complexity - O(1) |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="root"></param> |
| 3 | 26 | | public FindElementsInContaminatedBinaryTreeDepthFirstSearch(TreeNode root) |
| 3 | 27 | | { |
| 3 | 28 | | _root = root; |
| 3 | 29 | | _root.val = 0; |
| 3 | 30 | | } |
| | 31 | |
|
| | 32 | | /// <summary> |
| | 33 | | /// Time complexity - O(log n) |
| | 34 | | /// Space complexity - O(log n) |
| | 35 | | /// </summary> |
| | 36 | | /// <param name="target"></param> |
| | 37 | | /// <returns></returns> |
| | 38 | | public bool Find(int target) |
| 9 | 39 | | { |
| 9 | 40 | | var node = _root; |
| 9 | 41 | | var stack = new Stack<bool>(); |
| | 42 | |
|
| 23 | 43 | | while (target > 0) |
| 14 | 44 | | { |
| 14 | 45 | | stack.Push(target % 2 == 1); |
| | 46 | |
|
| 14 | 47 | | target = (target - 1) / 2; |
| 14 | 48 | | } |
| | 49 | |
|
| 17 | 50 | | while (stack.Count > 0) |
| 12 | 51 | | { |
| 12 | 52 | | node = stack.Pop() ? node.left : node.right; |
| | 53 | |
|
| 12 | 54 | | if (node == null) |
| 4 | 55 | | { |
| 4 | 56 | | return false; |
| | 57 | | } |
| 8 | 58 | | } |
| | 59 | |
|
| 5 | 60 | | return true; |
| 9 | 61 | | } |
| | 62 | | } |