| | | 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.EvaluateBooleanBinaryTree; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class EvaluateBooleanBinaryTreeDepthFirstSearch : IEvaluateBooleanBinaryTree |
| | | 18 | | { |
| | | 19 | | private const int OrOperation = 2; |
| | | 20 | | private const int AndOperation = 3; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Time complexity - O(n) |
| | | 24 | | /// Space complexity - O(n) for a skewed tree, O(n log n) for a balanced tree |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="root"></param> |
| | | 27 | | /// <returns></returns> |
| | | 28 | | public bool EvaluateTree(TreeNode? root) |
| | 8 | 29 | | { |
| | 8 | 30 | | return root != null && GetTreeEvaluation(root); |
| | 8 | 31 | | } |
| | | 32 | | |
| | | 33 | | private static bool GetTreeEvaluation(TreeNode root) |
| | 30 | 34 | | { |
| | 30 | 35 | | if (root.left == null && root.right == null) |
| | 15 | 36 | | { |
| | 15 | 37 | | return root.val == 1; |
| | | 38 | | } |
| | | 39 | | |
| | 15 | 40 | | var left = false; |
| | | 41 | | |
| | 15 | 42 | | if (root.left != null) |
| | 15 | 43 | | { |
| | 15 | 44 | | left = GetTreeEvaluation(root.left); |
| | | 45 | | |
| | 15 | 46 | | switch (root.val) |
| | | 47 | | { |
| | 8 | 48 | | case OrOperation when left: |
| | 4 | 49 | | return true; |
| | 7 | 50 | | case AndOperation when !left: |
| | 4 | 51 | | return false; |
| | | 52 | | } |
| | 7 | 53 | | } |
| | | 54 | | |
| | 7 | 55 | | var right = false; |
| | | 56 | | |
| | 7 | 57 | | if (root.right != null) |
| | 7 | 58 | | { |
| | 7 | 59 | | right = GetTreeEvaluation(root.right); |
| | 7 | 60 | | } |
| | | 61 | | |
| | 7 | 62 | | if (root.val == OrOperation) |
| | 4 | 63 | | { |
| | 4 | 64 | | return left | right; |
| | | 65 | | } |
| | | 66 | | |
| | 3 | 67 | | return left & right; |
| | 30 | 68 | | } |
| | | 69 | | } |