题目: 给定一个二叉树,检查其是否为镜像对称!
思路: 1.要设置一个镜像树,设原树为tree,镜像树为new_tree。
2.tree.left.val == new_tree.right.val and tree.right.val == new_tree.left.val,简单来讲就是左子树的左孩子 = 右子树的右孩子,左子树的右孩子 = 右子树的左孩子!
code:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
def new_trees(root_left, root_right): #以下三个if为递归终止的三个条件
if root_left == None and root_right:
return True
if root_left == None or root_right == None:
return False
if root_left.val != root_right.val:
return False
return new_tree(root_left.left, root_right.right) and new_tree(root_left.right, root_right.left)
return new_tree(root.left, root.right) #使用递归函数,分别比较左右节点!
时间复杂度:O(n),因为我们遍历整个输入树一次,所以总的运行时间为 O(n),其中 n 是树中结点的总数。
空间复杂度:O(n),递归调用的次数受树的高度限制。在最糟糕情况下,树是线性的,其高度为 O(n),因此,在最糟糕的情况下,由栈上的递归调用造成的空间复杂度为 O(n)。