Skip to content

Commit 90cc093

Browse files
authored
Merge pull request #1140 from ivan1016017/january02
invert binary tree
2 parents 34f3ef8 + 13c38ec commit 90cc093

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
11+
class Solution:
12+
def invertTree(self, root: TreeNode) -> TreeNode:
13+
14+
try:
15+
root.val
16+
except:
17+
return root
18+
19+
root.left, root.right = (
20+
self.invertTree(root.right),
21+
self.invertTree(root.left)
22+
)
23+
24+
return root
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import unittest
2+
from my_project.interviews.top_150_questions_round_12\
3+
.invert_binary_tree import Solution, TreeNode
4+
5+
class InvertTreeTestCase(unittest.TestCase):
6+
7+
def test_none_inverted_tree(self):
8+
solution = Solution()
9+
tree = None
10+
output = solution.invertTree(root=tree)
11+
self.assertIsNone(output)
12+
13+
def test_inverted_tree(self):
14+
solution = Solution()
15+
tree = TreeNode(1,TreeNode(2),TreeNode(3))
16+
output = solution.invertTree(root=tree)
17+
self.assertEqual(1,output.val)
18+
self.assertEqual(2,output.right.val)
19+
self.assertEqual(3,output.left.val)

0 commit comments

Comments
 (0)