Leetcode 100. The same tree | Python

Time:2020-11-21

100. The same tree


Source: leetcode https://leetcode-cn.com/problems/same-tree

subject


Given two binary trees, write a function to check whether they are the same.

Two trees are considered identical if they are structurally identical and nodes have the same value.

Example 1:

Input: 1 1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input: 1 1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input: 1 1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

Thinking of problem solving


From the meaning of the topic, if two binary trees are the same, then the two trees are the same in structure, and the nodes have the same value. Then, we can judge whether the two binary trees are the same by depth first search (DFS) and breadth first search (BFS).

Idea: DFS, BFS

Depth first search (DFS)

Using depth first search, the situation and analysis are as follows:

  • When two binary trees are empty, it can be determined that the two binary trees are the same and return true;
  • When one of the two binary trees is empty and the other is not, the two binary trees must be different, and return false;
  • When two binary trees are not empty, we should judge the value of the node. The root nodes of the two binary trees and the values of the left and right subtrees of the root nodes are judged respectively. If it is different, it indicates that the two binary trees are different, and returns false, otherwise it returns true.

For specific code, please refer to [code implementation depth first search]

Breadth first search (BFS)

Similarly, we can also use breadth first search to solve this problem. Here we need to use auxiliary queue. The specific process of the algorithm is as follows:

  • Judge whether two binary trees are empty at the same time. If so, return true;
  • Judge whether one of the two binary trees is empty and the other is not. If so, return false;
  • When two binary trees are not empty, breadth first search is started. Here, queues are used to store nodes of the two binary trees

    • First, the root nodes of the two binary trees are put into the queue;
    • Out of the queue, the values of the two nodes are compared

      • When the values of two nodes are different, the binary tree must be different;
      • When the values of two nodes are the same, continue to judge whether the structure of the binary tree is the same, that is, whether the child nodes of the current node are empty. If it is empty at the same time, it is determined to be the same. However, if only one child node of two nodes is empty, then the binary tree is different.
      • When the two nodes have the same value and structure, the non empty sub nodes of the two nodes are stored in the queue respectively. It should be noted here that when storing, if the child node is not empty, the order of consideration is from left to right.

After the execution of the previous algorithm, if the queue is empty, then the two binary trees are the same; if the queues are not all empty, it indicates that the structure of the binary tree is different, that is to say, the two binary trees are different.

For specific code, see code implementation breadth first search

code implementation


#Depth first search
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        
        def dfs(p, q):
            #When two binary trees are empty
            if p == None and q == None:
                return True
            #When only one of two binary trees is empty
            elif p == None or q == None:
                return False
            #If the binary tree is not empty, compare the value
            elif p.val == q.val:
                #When the value of the root node is the same, continue to judge the value of the left and right subtrees
                return dfs(p.left, q.left) and dfs(p.right, q.right)
            #If the value is different, false is returned
            return False
            

        return dfs(p, q)

#Breadth first search
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        from collections import deque
        #Judge whether two binary trees are empty
        if not p and not q:
            return True
        elif not p or not q:
            return False
        #If they are not empty, the queue is used to store the nodes of the binary tree
        #Join the two root nodes first
        queue_p = deque([p])
        queue_q = deque([q])

        while queue_p and queue_q:
            node_p = queue_p.popleft()
            node_q = queue_q.popleft()
            
            #Comparison value
            if node_p.val != node_q.val:
                return False
            #Comparative structure
            left_p, right_p = node_p.left, node_p.right
            left_q, right_q = node_q.left, node_q.right
            #Here, XOR is used to directly judge whether two are empty and one of them is null
            #Return 0 if ^ same, otherwise return 1
            #The statement will be executed only if 1 is returned, that is, false is returned
            if (not left_p) ^ (not left_q):
                return False
            if (not right_p) ^ (not right_q):
                return False
            #When the value is the same as the structure, the child nodes are queued from left to right when the child node is not empty
            if left_p:
                queue_p.append(left_p)
            if right_p:
                queue_p.append(right_p)
            if left_q:
                queue_q.append(left_q)
            if right_q:
                queue_q.append(right_q)
        
        #Finally, we need to judge whether the queue is empty
        #If the queues are not all empty, the binary tree structure is different
        return not queue_p and not queue_q

Achieving results


Leetcode 100. The same tree | Python

Leetcode 100. The same tree | Python

Welcome to our attention


The official account [book collection]