All Elements in Two Binary Search Trees — Day 108(Python)

Photo by veeterzy on Unsplash

Today’s question is from the daily leetcode challenge. Let us look into the problem statement.

Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.

Example 1:

Example 2:

Constraints:

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

One way to solve this problem would be, to add all the values of the nodes from both the trees into a list, and then can use python’s inbuilt sort function to sort the list.

Complexity Analysis

Time Complexity

We are creating a list of node values from both the trees and then using python’s inbuilt sort function to sort our list. Hence the time complexity is (M+N) log(M+N), where M and N are the number of nodes in both the trees.

Space Complexity

We are creating a list of node values from both the trees, hence the space complexity is O(M+N).

Can we not use the sort function? Since we are given binary search trees, we can use in-order traversal and get a sorted list. If you need to read more about the Binary Search tree, you can follow this link.

Once we have both the sorted list, we can compare the first element in both the lists and the add the smaller among two elements to our output list. We will keep doing this until both our sorted lists are empty.

Complexity Analysis

Time Complexity

We are creating two sorted list by traversing through both the binary search trees. The traversal takes O(M+N), where M and N are the number of nodes in both the trees. After getting the sorted list, we are comparing the elements in both the list, which takes O(M+N). Hence time complexity is O(M+N).

Space Complexity

We are creating a list of node values from both the trees, hence the space complexity is O(M+N).

--

--

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store