Leetcode Brush Questions--101. Symmetric Binary Tree

One little white, go directly to the comment area to learn:
Attach a link to the
problem solution link: https://leetcode-cn.com/problems/symmetric-tree/solution/bfs-dui-lie-tong-shi-bao-cun-bao- cun-yao-pan-duan-/
Binary tree realization link: https://blog.csdn.net/Tonywu2018/article/details/89480282

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

 

例如,二叉树 [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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import collections


class TreeNode(object):
    def __init__(self, data=0, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right


class BinTree(object):
    def __init__(self):
        self.root = None
        self.ls = []

    def add(self, data):
        node = TreeNode(data)
        if self.root is None:
            self.root = node
            self.ls.append(self.root)
            return
        treenode = self.ls[0]
        if treenode.left is None:
            treenode.left = node
            self.ls.append(node)
        elif treenode.right is None:
            treenode.right = node
            self.ls.append(node)
            self.ls.pop(0)

    def preOrederTraversal(self, root):
        if root is None:
            return
        print(root.data)
        self.preOrederTraversal(root.left)
        self.preOrederTraversal(root.right)


class Solution(object):
    def isSymmetric(self, Troot: BinTree) -> bool:
        queue = collections.deque()
        queue.append((Troot.root.left, Troot.root.right))
        while queue:
            left, right = queue.popleft()
            if not left and not right:
                continue
            if not left or not right:
                return False
            if left.data != right.data:
                return False
            queue.append((left.left, right.right))
            queue.append((left.right, right.left))
        return True


if __name__ == '__main__':
    L = [1, 2, 2, 3, 4, 4, 3]
    Tree = BinTree()
    for i in L:
        Tree.add(i)
    solution = Solution()
    print(solution.isSymmetric(Tree))

This code contains a simple implementation of the binary tree, mainly to exercise the code ability, not only to write problem solutions, but also to write examples.
The following are questions and answers during the learning process:

Q: What is queue = collections.deque()?
deque is a double-ended queue. If you want to append data from both ends frequently, it is better to choose this data structure. If you want to achieve random access, it is not recommended to use this, please use a list. The
advantage of deque is that you can append and appendleft from both sides Data. There is no list at this point.
Read the official document in English
https://docs.python.org/3.6/library/collections.html#collections.deque

Q: What is queue.popleft()?
Pop from the left

Q: queue.append((root, root))
left, right = queue.popleft() In
this code, isn't it a tuple added? Why can popleft pop up twice?
Isn't left and right shorthand for tuples here?

Q: queue.append((left.left, right.right))
queue.append((left.right, right.left))
left, right = queue.popleft()
What are the values ​​of left and right?
If you pass in (1, 1)
Left=1
Right=1
(1, 1) is left in the queue

Idea: Symmetry is very simple. That is, for nodes with the same parent node,
1. The left child node of the left node must have the same value as the right child node of the right node,
2.The right child node of the left node must have the same value as the left child node of the right node.

Q: Python binary tree realizes the basic structure and additional operations?
There is no concept of structure in Python, so a class is needed, and there is only the basic __init__(self, data) method in the class to build tree nodes.

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

Another class is used to represent the binary tree, and the list of definitions in the binary tree is used to store node addresses that can also increase child nodes.

class BinTree(object):
    def __init__(self):
        self.root = None	# 初始化根节点为None,理解为指向一个TreeNode类的指针。
        self.ls = []	# 定义列表,用于存储节点地址

    def add(self, data):
    	# 用add方法向树结构中添加元素
        node = TreeNode(data)	# 实例化一个树节点
        if self.root is None:	# 若根节点不存在,添加根节点
            self.root = node
            self.ls.append(self.root)	# 这里,增加了根节点地址,因为Python没有指针,对应下面的pop(0)
            return
        treenode = self.ls[0]
        if treenode.left is None:
            treenode.left = node
            self.ls.append(node)
        elif treenode.right is None:
            treenode.right = node
            self.ls.append(node)
            self.ls.pop(0)	# 这里,当右子节点添加完毕后,该节点无法添加节点,所以将该节点的地址删除。
            # 这样,列表中剩下的就只有还能添加子节点的节点了

    def preOrederTraversal(self, root):
        if root is None:
            return
        print(root.data)
        self.preOrederTraversal(root.left)
        self.preOrederTraversal(root.right)

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/113113606