題目
原題頁面: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 | 1 |
But the following is not:
1 | 1 |
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 | 1 |
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
分析
最開始想到的方法是進行二叉樹的層次遍歷,判斷每一層的節點列表是不是左右對稱的。但題目建議用遞歸回溯,但是如何在遞迴中判斷對稱的確不容易想到。
就這道題目而言,其實也是遞迴地判斷每組對稱的兩點是否相等。
程式碼
1 | class Solution: |
