From 5cc95fb77a71cfe2c7dab9487445db1360e808ba Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 27 Nov 2024 04:29:04 -0600 Subject: [PATCH] adding invert binary tree --- .../invert_binary_tree.py | 23 +++++++++++++++++++ .../test_invert_binary_tree_round_11.py | 19 +++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_11/invert_binary_tree.py create mode 100644 tests/test_150_questions_round_11/test_invert_binary_tree_round_11.py diff --git a/src/my_project/interviews/top_150_questions_round_11/invert_binary_tree.py b/src/my_project/interviews/top_150_questions_round_11/invert_binary_tree.py new file mode 100644 index 00000000..c7172956 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_11/invert_binary_tree.py @@ -0,0 +1,23 @@ +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_11/test_invert_binary_tree_round_11.py b/tests/test_150_questions_round_11/test_invert_binary_tree_round_11.py new file mode 100644 index 00000000..a7dfbfb8 --- /dev/null +++ b/tests/test_150_questions_round_11/test_invert_binary_tree_round_11.py @@ -0,0 +1,19 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_11\ +.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