Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2925c84

Browse files
Coding SOlution of symmetric tree
1 parent 8dcfc2b commit 2925c84

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
9+
def isMirror(root1, root2):
10+
# If both trees are empty, then they are mirror images
11+
if root1 is None and root2 is None:
12+
return True
13+
14+
""" For two trees to be mirror images,
15+
the following three conditions must be true
16+
1 - Their root node's key must be same
17+
2 - left subtree of left tree and right subtree
18+
of the right tree have to be mirror images
19+
3 - right subtree of left tree and left subtree
20+
of right tree have to be mirror images
21+
"""
22+
if (root1 is not None and root2 is not None):
23+
if root1.val == root2.val:
24+
return (isMirror(root1.left, root2.right) and
25+
isMirror(root1.right, root2.left))
26+
# If none of the above conditions is true then root1
27+
# and root2 are not mirror images
28+
return False
29+
30+
return isMirror(root, root)
31+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /