给你一个二叉树的根节点 root , 检查它是否轴对称。
解题思路:
1.自己的写法
- 原来由于不会两棵树同时遍历,于是分开遍历,将各自遍历的结果分别存入各自的数组,比较这两个数组的值;
- 左边的子树采用的是前左右的遍历方式,右边的子树采用的是前右左的遍历方式;
- 最后比较两个数组元素是不是相等。
class Solution(object):
def isSymmetric(self, root):
"""
:type root: Optional[TreeNode]
:rtype: bool
"""
if not root:
return False
#左右子树
left = root.left
right = root.right
#存储遍历的值
left1 = list()
right1 = list()
#判断是否一开始左右子树为空
if left and right and left.val != right.val:
return False
#左边子树遍历函数
def post1(root1):
if not root1:
left1.append(None)
return
left1.append(root1.val)
post1(root1.left)
post1(root1.right)
#右边子树遍历函数
def post2(root2):
if not root2:
right1.append(None)
return
right1.append(root2.val)
post2(root2.right)
post2(root2.left)
#遍历
post1(left)
post2(right)
#判断两数组是否相同
return left1 == right1
2.递归解法
- 知道了如何同时对两颗树进行遍历,还是采用上面对称遍历的做法;
- 递归终止条件:
- 返回True(对称)情况:两个节点都为空(True);
- 返回False(不对称)情况:只有其中一个节点为空;左子树与右子树中节点值不相等。
class Solution(object):
def isSymmetric(self, root):
"""
:type root: Optional[TreeNode]
:rtype: bool
"""
def recur(r1,r2):
#遍历终止条件,两颗树都遍历到了叶子节点
if not r1 and not r2:
return True
#其中一棵树到叶子节点,另一棵树还有值
if not r1 or not r2:
return False
#遍历过程中判断左右树的值是否相同,然后两棵树镜像遍历
return r1.val == r2.val and recur(r1.left,r2.right) and recur(r1.right,r2.left)
return recur(root.left,root.right)