Skip to content

Commit 5ce233c

Browse files
authored
Merge pull request #1352 from ivan1016017/august03
adding symmetric tree
2 parents 61fc8d9 + eb6db9f commit 5ce233c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
class Solution:
11+
12+
def isSymmetric(self, root: TreeNode) -> bool:
13+
return self.check_mirror(root1=root, root2=root)
14+
15+
def check_mirror(self, root1: TreeNode, root2: TreeNode):
16+
17+
if root1 is None and root2 is None:
18+
return True
19+
elif root1 is not None and root2 is not None:
20+
try:
21+
root1.val
22+
root2.val
23+
except:
24+
return False
25+
26+
if root1.val != root2.val:
27+
return False
28+
else:
29+
return self.check_mirror(root1.left, root2.right) \
30+
and self.check_mirror(root1.right, root2.left)
31+
else:
32+
return False
33+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_18\
3+
.symmetric_tree import TreeNode, Solution
4+
5+
class SymmetricTreeTestCase(unittest.TestCase):
6+
7+
def test_is_symmetric(self):
8+
solution = Solution()
9+
output = solution.isSymmetric(TreeNode(1, TreeNode(7), TreeNode(7)))
10+
self.assertTrue(output)
11+
12+
def test_is_no_symmetric(self):
13+
solution = Solution()
14+
output = solution.isSymmetric(TreeNode(1, TreeNode(2), TreeNode(3)))
15+
self.assertFalse(output)

0 commit comments

Comments
 (0)