对称二叉树

时间:2022-07-22
本文章向大家介绍对称二叉树,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Day49: 对称二叉树

题目

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/symmetric-tree/submissions/

# 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
        """

错误代码

判断二叉树是否对称,先看看下面代码是否正确,它实现的什么功能?

首先看递归基,分三种情况:

  1. 没有根,就是空树,返回True
  2. 没有左右子树,返回True
  3. 左右子节点val不相等,返回False

递归方程如下,判断左、右子树都对称。

self.isSymmetric(root.left) and self.isSymmetric(root.right)
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True 
        if not root.left and not root.right:
            return True 
        return root.left == root.right and self.isSymmetric(root.left) and self.isSymmetric(root.right)

以上代码认为下面的二叉树才是对称的:

这与题目要求的对称二叉树明显不同,这样才是真的对称二叉树:

正确代码

错误代码错误的原因在于递归方程有问题。请看下图:

因此,得到正确的递归方程:

sub(left.left,right.right) and sub(left.right,right.left)

完整代码:

class Solution(object):
    def isSymmetric(self, root):
        if not root:
            return True 
        def sub(left,right):
            # 没有左和右,返回True
            if not left and not right:
                return True
            # 没有左或没有右,返回False
            if not left or not right:
                return False
            return left.val == right.val and sub(left.left,right.right) and sub(left.right,right.left)
        return sub(root.left,root.right)