LeetCode刷题第八天(101、对称二叉树easy)

目录

一、题目:

示例 1:

示例 2:

提示:

二、思路:

1、树

2、python中[-1]、[:-1]、[::-1]、[n::-1]使用方法

 3、具体思路:

方法一:

方法二:

三、代码:

 方法一:

 方法二:


一、题目:

给你一个二叉  树的根节点 root , 检查它是否轴对称。

示例 1:


输入:root = [1,2,2,3,4,4,3]
输出:true


示例 2:


输入:root = [1,2,2,null,3,null,3]
输出:false
 

提示:

树中节点数目在范围 [1, 1000] 内
-100 <= Node.val <= 100

二、思路:

1、树

可以看看这篇文章,对python中的树的表达有了解。

树--- python实现_python实现树_茨球是只猫的博客-CSDN博客

知道了树的结构,本质上就是对比两个位于一左一右的结点是否一样.

补充一个知识:

2、python中[-1]、[:-1]、[::-1]、[n::-1]使用方法

import numpy as np
a=np.random.rand(5)
print(a)
[ 0.64061262  0.8451399   0.965673    0.89256687  0.48518743]
 
print(a[-1]) ###取最后一个元素
[0.48518743]
 
print(a[:-1])  ### 除了最后一个取全部
[ 0.64061262  0.8451399   0.965673    0.89256687]
 
print(a[::-1]) ### 取从后向前(相反)的元素
[ 0.48518743  0.89256687  0.965673    0.8451399   0.64061262]
 
print(a[2::-1]) ### 取从下标为2的元素翻转读取
[ 0.965673  0.8451399   0.64061262]

 3、具体思路:

方法一:

我们可以用使用层次遍历的方式,层序遍历找出来,判断每一层是不是回文数组。 

注意:跟普通的层序遍历不一样的地方在于:如果是空结点,也要把None添加到层序遍历的结果数组里。

方法二:

第二种方式是 递归方式,核心思想是 将  两个node一左一右地对比是不是一样。

三、代码:

 方法一:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        queue=[root]
        while queue:
            next_queue=[]
            now_queue=[]
            for node in queue:
                if not node:
                    now_queue.append(None)
                    continue
                next_queue.append(node.left)
                next_queue.append(node.right)
                now_queue.append(node.val)
            if now_queue!=now_queue[::-1]:
                return False
            queue=next_queue
        return True

 方法二:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def check(node1, node2):
            if not node1 and not node2:
                return True
            elif not node1 or not node2:
                return False

            if node1.val != node2.val:
                return False
            return check(node1.left, node2.right) and check(node1.right, node2.left)

        return check(root, root)

 

猜你喜欢

转载自blog.csdn.net/m0_51786204/article/details/129908448