【Leetcode笔记】对称二叉树

Leetcode原题链接:
对称二叉树

一、思路

  • 后序遍历(左右中),递归最好理解,先比子节点,若对称再返回True,继续向上比较
  • 实际上迭代遍历和层序遍历也可以实现,具体看代码吧,有点难描述。。

二、代码

1、递归遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        return self.compare(root.left, root.right)

    def compare(self, l_node, r_node):
        if not l_node and not r_node:
            return True
        elif not l_node and r_node:
            return False
        elif l_node and not r_node:
            return False
        elif l_node.val != r_node.val:
            return False
        else:
            outside = self.compare(l_node.left, r_node.right)
            inside = self.compare(l_node.right, r_node.left)
            result = (outside and inside)
            return result

2、迭代遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        queue = []
        queue.append(root.left)
        queue.append(root.right)
        while queue:
            l_node = queue.pop(0)
            r_node = queue.pop(0)
            if not l_node and not r_node:
                continue
            if not l_node or not r_node or l_node.val != r_node.val:
                return False
            queue.append(l_node.left)
            queue.append(r_node.right)
            queue.append(l_node.right)
            queue.append(r_node.left)
        return True
  • 迭代遍历的话,最初放入队列的节点就不只是根节点了,放的是根节点的左右孩子节点
  • 每次加入队列也是分别按照对称的顺序加入左右孩子节点的子节点

3、层序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        queue = [root.left, root.right]
        while queue:
            size = len(queue)
            if size%2 != 0:
                return False
            tmp = []
            for i in range(size):
                node = queue.pop(0)
                if node:
                    tmp.append(node.val)
                    queue.append(node.left)
                    queue.append(node.right)
                else:
                    tmp.append(None)
            if tmp != tmp[::-1]:
                return False
        return True
  • 层序遍历感觉还挺神奇,先判断每一层数量,不能被 2 整除必然False
  • 然后就把当前层的节点值加入列表中,如果是空,也要加入None每一层遍历完后,根据python比较独特的切片方法,判断列表和它反转后是否相同,相同则为对称

三、总结

  • 二叉树的许多题目都与遍历有关,遇到二叉树的题多思考思考,根据遍历来解决问题。

部分内容参考代码随想录

你可能感兴趣的:(leetcode,笔记,算法)