Skip to content

Commit e9b069c

Browse files
committed
O(n) time and O(n) space using recursion.
1 parent 1a90de9 commit e9b069c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
3+
4+
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
5+
6+
1
7+
/ \
8+
2 2
9+
/ \ / \
10+
3 4 4 3
11+
12+
13+
But the following [1,2,2,null,3,null,3] is not:
14+
15+
1
16+
/ \
17+
2 2
18+
\ \
19+
3 3
20+
21+
22+
Follow up: Solve it both recursively and iteratively.
23+
"""
24+
25+
26+
# Definition for a binary tree node.
27+
# class TreeNode:
28+
# def __init__(self, val=0, left=None, right=None):
29+
# self.val = val
30+
# self.left = left
31+
# self.right = right
32+
class Solution:
33+
def isSymmetric(self, root: TreeNode) -> bool:
34+
if not root:
35+
return True
36+
37+
def symmetric(root1, root2):
38+
if not root1 and not root2:
39+
return True
40+
if (not root1 and root2) or (root1 and not root2):
41+
return False
42+
if root1.val != root2.val:
43+
return False
44+
return symmetric(root1.left, root2.right) and symmetric(root1.right, root2.left)
45+
46+
return symmetric(root.left, root.right)

0 commit comments

Comments
 (0)