diff --git a/src/my_project/interviews/top_150_questions_round_17/invert_binary_tree.py b/src/my_project/interviews/top_150_questions_round_17/invert_binary_tree.py new file mode 100644 index 00000000..8b5245a4 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_17/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 diff --git a/tests/test_150_questions_round_17/test_invert_binary_tree_round_17.py b/tests/test_150_questions_round_17/test_invert_binary_tree_round_17.py new file mode 100644 index 00000000..81e86b50 --- /dev/null +++ b/tests/test_150_questions_round_17/test_invert_binary_tree_round_17.py @@ -0,0 +1,19 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_17\ +.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