简繁EN

LeetCodeNo. 103

【LeetCode with Python】 101. Symmetric Tree

目錄

題目

原題頁面:https://leetcode.com/problems/symmetric-tree/
題目型別:Tree, Depth-first Search
難度評價: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}".


分析

最開始想到的方法是進行二叉樹的層次遍歷,判斷每一層的節點列表是不是左右對稱的。但題目建議用遞歸回溯,但是如何在遞迴中判斷對稱的確不容易想到。
就這道題目而言,其實也是遞迴地判斷每組對稱的兩點是否相等。


程式碼

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)

本文地址:https://xnerv.wang/zh-tw/leetcode-symmetric-tree/