From 3a9f390f9384db12dfdc82462b375c25b5d01842 Mon Sep 17 00:00:00 2001 From: ivan Date: Sun, 12 Oct 2025 04:24:45 -0600 Subject: [PATCH] adding algo --- .../invert_binary_tree.py | 22 +++++++++++++++++++ .../test_invert_binary_tree_round_20.py | 19 ++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_20/invert_binary_tree.py create mode 100644 tests/test_150_questions_round_20/test_invert_binary_tree_round_20.py diff --git a/src/my_project/interviews/top_150_questions_round_20/invert_binary_tree.py b/src/my_project/interviews/top_150_questions_round_20/invert_binary_tree.py new file mode 100644 index 00000000..99dec73c --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_20/invert_binary_tree.py @@ -0,0 +1,22 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + + try: + root.val + except: + return root + + root.left, root.right = ( + self.invertTree(root.right), self.invertTree(root.left) + ) + + return root \ No newline at end of file diff --git a/tests/test_150_questions_round_20/test_invert_binary_tree_round_20.py b/tests/test_150_questions_round_20/test_invert_binary_tree_round_20.py new file mode 100644 index 00000000..2f49172a --- /dev/null +++ b/tests/test_150_questions_round_20/test_invert_binary_tree_round_20.py @@ -0,0 +1,19 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_20\ +.invert_binary_tree import TreeNode, Solution + +class InvertTreeTestCase(unittest.TestCase): + + def test_none_inverted_tree(self): + solution = Solution() + tree = None + output = solution.invertTree(root=tree) + self.assertIsNone(output) + + def test_inverted_tree(self): + solution = Solution() + tree = TreeNode(1,TreeNode(2),TreeNode(3)) + output = solution.invertTree(root=tree) + self.assertEqual(1,output.val) + self.assertEqual(2,output.right.val) + self.assertEqual(3,output.left.val) \ No newline at end of file