1、題目描述
https://leetcode-cn.com/problems/symmetric-tree/
給定一個二叉樹,檢查它是否是鏡像對稱的。
2、代碼詳解
2.1 遞歸寫法
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# 遞歸寫法
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.isMirror(root, root)
def isMirror(self, root1, root2):
# 遞歸結束條件
if not root1 and not root2: # 條件1:都爲空指針則返回 true
return True
elif not root1 or not root2: # 條件2:只有一個爲空則返回 false
return False
return (root1.val == root2.val) and \
self.isMirror(root1.left, root2.right) and \
self.isMirror(root1.right, root2.left)
pNode1 = TreeNode(1)
pNode2 = TreeNode(2)
pNode3 = TreeNode(2)
pNode4 = TreeNode(3)
pNode5 = TreeNode(4)
pNode6 = TreeNode(4)
pNode7 = TreeNode(3)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7
S = Solution()
print(S.isSymmetric(pNode1)) # True
時間複雜度是 O(n),因爲要遍歷 n 個節點
空間複雜度是 O(n),是遞歸的深度,也就是跟樹高度有關,最壞情況下樹變成一個鏈表結構,高度是n。
2.2 迭代寫法
用隊列來實現
- 首先從隊列中拿出兩個節點(left 和 right)比較
- 將 left 的 left 節點和 right 的 right 節點放入隊列
- 將 left 的 right 節點和 right 的 left 節點放入隊列
時間複雜度是 O(n),空間複雜度是 O(n)
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root or not (root.left or root.right):
return True
# 用隊列保存節點
queue = [root.left,root.right]
while queue:
# 從隊列中取出兩個節點,再比較這兩個節點
left = queue.pop(0)
right = queue.pop(0)
# 如果兩個節點都爲空就繼續循環,兩者有一個爲空就返回false
if not (left or right):
continue
if not (left and right):
return False
if left.val!=right.val:
return False
# 將左節點的左孩子, 右節點的右孩子放入隊列
queue.append(left.left)
queue.append(right.right)
# 將左節點的右孩子,右節點的左孩子放入隊列
queue.append(left.right)
queue.append(right.left)
return True