对称的二叉树
描述 给定一棵二叉树,判断其是否是自身的镜像(即:是否对称)
数据范围:节点数满足 0≤n≤1000,节点上的值满足∣val∣≤1000 要求:空间复杂度 O(n),时间复杂度 O(n) 备注: 你可以用递归和迭代两种方法解决这个问题
思路:题目挺简单的,将pRoot分成左子树leftTree和右子树rightTree,leftTree的每一个子树的左边节点left的值等于rightTree的每一个子树的右边节点right的值,leftTree的每一个的右边节点right的值等于rightTree的左边节点left的值,递归一下就行了。
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
class Solution:
def isBanceTree(self,leftTree,rightTree):
if (leftTree == None) & (rightTree == None):
return True
elif (leftTree != None) & (rightTree == None):
return False
elif (leftTree == None) & (rightTree != None):
return False
elif leftTree.val != rightTree.val:
return False
else:
return self.isBanceTree(leftTree.left, rightTree.right) & self.isBanceTree(leftTree.right, rightTree.left)
def isSymmetrical(self , pRoot: TreeNode) -> bool:
# write code here
if pRoot == None:
return True
return self.isBanceTree(pRoot.left, pRoot.right)