简繁EN

LeetCodeNo. 103

[LeetCode with Python] 101. Symmetric Tree

Contents

Problem

Problem page: https://leetcode.com/problems/symmetric-tree/
Topics: Tree, Depth-first Search
Difficulty: Easy

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

1
2
3
4
5
    1
/ \
2 2
/ \ / \
3 4 4 3

But the following is not:

1
2
3
4
5
  1
/ \
2 2
\ \
3 3

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means?

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

1
2
3
4
5
6
7
  1
/ \
2 3
/
4
\
5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".


Analysis

My first thought was to use level-order traversal on the binary tree and check whether the list of nodes at each level was symmetric from left to right. The problem suggests using recursion and backtracking. I had a hard time figuring out how to check for symmetry that way.
The recursion just compares the values of each pair of nodes in mirror positions.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:

def checkSysmmetric(self, left, right):
if None == left and None == right:
return True
elif None == left or None == right:
return False
elif left.val != right.val:
return False
return self.checkSysmmetric(left.left, right.right) and self.checkSysmmetric(left.right, right.left)

# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if None == root:
return True
return self.checkSysmmetric(root.left, root.right)

Article link: https://xnerv.wang/en/leetcode-symmetric-tree/