LeetCode 101. 对称二叉树
101. Symmetric Tree
Difficulty: 简单
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3]
则不是镜像对称的:
1
/ \
2 2
\ \
3 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
Solution
Language: 全部题目
错误解法一:[1,2,2,2,null,2]
,无法通过,中序遍历这棵树返回的列表结果可能是[2,2,1,2,2]而不是[2,2,'',1,2,2,'']
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
nodeList = inOrderTraversal(root)
if len(nodeList) % 2 == 0: # 如果列表的长度不是偶数,说明不是对称的树
return False
else:
for i in range(len(nodeList) // 2):
if nodeList[i] != nodeList[len(nodeList)-1-i]:
return False
return True
def inOrderTraversal(tree):
if not tree:
return [""]
else:
l = inOrderTraversal(tree.left)
d = [""] if not tree.val else [tree.val]
r = inOrderTraversal(tree.right)
return l + d + r
正确解法(看的答案),依然还是递归的方法
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
else:
return isSymmetricHelper(root.left, root.right)
def isSymmetricHelper(lTree, rTree):
if not lTree or not rTree:
return lTree == rTree
if lTree.val != rTree.val:
return False
return isSymmetricHelper(lTree.left, rTree.right) and isSymmetricHelper(lTree.right, rTree.left)