【LeetCode】1305. All Elements in Two Binary Search Trees

Author: Negative Snow Mingzhu
id: fuxuemingzhu
Personal blog: http://fuxuemingzhu.cn/
Keywords: LeetCode, LeetCode, solution, clear explanation, algorithm, binary tree, binary search tree, merge, Python


Topic address: https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees/

topic description

Given you  root1and root2 these two binary search trees. Please return a list containing  all integers in both trees  sorted in ascending order. .

 

Example 1:

insert image description here

Input: root1 = [2,1,4], root2 = [1,0,3]
 Output: [0,1,1,2,3,4]

Example 2:

Input: root1 = [1,null,8], root2 = [8,1]
 Output: [1,1,8,8]

 

hint:

  • The number of nodes per tree is in  [0, 5000]the range
  • -105 <= Node.val <= 105

Topic to the effect

Merge all the elements of the two binary search trees into an ordered array.

problem solving method

Method 1: Inorder traversal + merge

Idea: Keep in mind that the inorder traversal of a binary search tree is in order.

This sentence has appeared in each of my solutions to binary search trees (BST), because this is the key to solving BST.

Therefore, the in-order traversal of the two binary search trees can be performed separately to obtain two ordered arrays . Then merge the two sorted arrays.

The code for merging two sorted arrays can refer to Merge Sort.

There are also related topics on LeetCode:

# 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 getAllElements(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: List[int]
        """
        nums1 = []
        nums2 = []
        self.inOrder(root1, nums1)
        self.inOrder(root2, nums2)
        return self.merge(nums1, nums2)
        
        
    def inOrder(self, root, nums):
        if not root:
            return
        self.inOrder(root.left, nums)
        nums.append(root.val)
        self.inOrder(root.right, nums)
    
    def merge(self, nums1, nums2):
        res = []
        p1 = 0
        p2 = 0
        while p1 < len(nums1) and p2 < len(nums2):
            if nums1[p1] < nums2[p2]:
                res.append(nums1[p1])
                p1 += 1
            else:
                res.append(nums2[p2])
                p2 += 1
        if p1 < len(nums1):
            res.extend(nums1[p1:])
        if p2 < len(nums2):
            res.extend(nums2[p2:])
        return res

the complexity

  • Time complexity: O ( M + N ) O(M + N)O(M+N)
  • Space complexity: O ( M + N ) O(M + N)O(M+N)

Summarize

  1. This question examines three knowledge points: the nature of BST, in-order traversal, and merging two ordered arrays. They are all basic questions, which shows the importance of basic knowledge.

date

May 1, 2022 - the working people's holiday, start from writing questions!

Guess you like

Origin blog.csdn.net/fuxuemingzhu/article/details/124523032