LeetCode's same tree (100), subtree of another tree (572), merged binary tree (617)

1. The same tree (100)

Title description:

【simple】

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

If two trees are identical in structure and the nodes have the same value, they are considered the same.

Example 1:

输入:       1         1
          / \       / \
         2   3     2   3

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

输出: true

Topic link

Thinking analysis:

1. If both binary trees are empty, the two binary trees are the same. If one and only one of the two binary trees is empty, the two binary trees must be different.

2. If the two binary trees are not empty, first judge whether the values ​​of their root nodes are the same. If they are not the same, the two binary trees must be different. If they are the same, judge whether the left subtrees of the two binary trees are the same and whether Whether the subtrees are the same. This is a recursive process, so depth-first search can be used to recursively determine whether two binary trees are the same.

# 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:
        if not p and not q:
            return True
        elif not p or not q:
            return False
        else:
            if p.val!=q.val:
                return False
            else:
                return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
  • Time complexity: O (min ⁡ (m, n)) O(\min(m,n))O ( min ( m ,n))
  • Space complexity: O (min ⁡ (m, n)) O(\min(m,n))O ( min ( m ,n))

2. Subtree of another tree (572)

Title description:

【simple】

Given two non-empty binary trees s and t, check whether s contains a subtree with the same structure and node value as t. A subtree of s includes a node of s and all descendants of this node. s can also be regarded as a subtree of itself.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2

Given tree t:

   4 
  / \
 1   2

Returns true because a subtree of t and s has the same structure and node values.
Topic link

Thinking analysis:

1. To judge the subtree, you can use the same tree as the previous one.
2. If the two trees s and t are empty, it must be True.
3. If s and t are empty, it must be no.
4. Otherwise, judge s and t. Are they the same or whether the left subtree of s is the same as t, and the right subtree of s is the same as t.

class Solution:
    def identical(self, node_a, node_b):  # 判定两棵树是否相同
        if not node_a and not node_b:  # 两个 node 都为空为 True
            return True
        if node_a is None or node_b is None:  # 一方空,一方不空,为False
            return False
        # 否则说明两个 node 都非空,那么如果两个树相等必须满足3个条件,即当前 node 的值相等,且各自左右子树也对应相等
        return node_a.val == node_b.val and \
               self.identical(node_a.left, node_b.left) and \
               self.identical(node_a.right, node_b.right)
    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
        if not s:
            return False  # 边界,如果s为空直接返回False

        if self.identical(s, t):  # 若 s 和 t 对应的两棵树相同则返回True
            return True
        # 不然的话就继续探索 s 的左右子树是否和 t 相等
        return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)

3. Merging binary trees (617)

Title description:

【simple】

Given two binary trees, imagine that when you overlay one of them on the other, some nodes of the two binary trees will overlap.

You need to merge them into a new binary tree. The rule of merging is that if two nodes overlap, their values ​​are added as the new value after the node is merged, otherwise the node that is not NULL will be directly used as the node of the new binary tree.

Example 1:

输入: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并后的树:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

Note: The merge must start from the root node of the two trees.
Topic link

Thinking analysis:

1. Corresponding nodes of two binary trees may have the following three situations, and different merging methods are used for each situation.

  • If the corresponding nodes of the two binary trees are empty, the corresponding nodes of the merged binary tree are also empty;

  • If only one of the corresponding nodes of the two binary trees is empty, the corresponding node of the merged binary tree is the non-empty node;

  • If the corresponding nodes of the two binary trees are not empty, the value of the corresponding node of the merged binary tree is the sum of the values ​​of the corresponding nodes of the two binary trees. At this time, the two nodes need to be merged explicitly.

2. After merging a node, the left and right subtrees of the node must be merged separately. This is a recursive process.

# 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 mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
        if not t1:
            return t2
        elif not t2:
            return t1
        elif not t1 and not t2:
            return t1
        root=TreeNode(t1.val+t2.val)
        root.left=self.mergeTrees(t1.left,t2.left)
        root.right=self.mergeTrees(t1.right,t2.right)
        return root
  • Time complexity: O (min (m, n)) O(min(m,n))O ( m i n ( m ,n))
  • Space complexity: O (min (m, n)) O(min(m,n))O ( m i n ( m ,n))

Guess you like

Origin blog.csdn.net/weixin_45666566/article/details/113315986
Recommended