Equality of two binary search trees constructed from unordered arrays

后端 未结 4 1986
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 02:24

Given two unsorted arrays of size N each, we are to determine if the Binary Search Tree constructed from them will be equal or not.

So, the elements of

4条回答
  •  被撕碎了的回忆
    2021-02-15 03:22

    Summary

    I think you can improve the naive approach from O(N^2) to O(NlogN) by using range minimum query to construct the binary tree.

    Fast binary tree construction

    Suppose we want to construct the binary tree for an array A.

    The idea is to first construct an array B where B[i] is the position of the ith largest element in A. This can be done by sorting in O(NlogN).

    We can then use range minimum query on array B to allow us to find the minimum value of B[i] for a given range a<=i<=b. In other words, this lets us find the first position in A where we have a value in the range between the ath and bth largest elements.

    RMQ takes time O(N) to preprocess, and then queries can be answered in time O(1).

    We can then recursively find for each element its left and right children (if any) and check that they match.

    Pseudocode

    Suppose the two arrays are A and A2, and we assume for simplicity that A,A2 have been preprocessed such that the ith largest element is equal to i.

    The trees are identical if find_children(1,N) is True:

    find_children(low,high)
       if high==low
          return True
       node = A[RMQ(low,high)]
       return node == A2[RMQ2(low,high)]
              and find_children(low,node-1)
              and find_children(node+1,high)
    

    This function is called once for each node (and empty child pointer) in the tree so takes time O(N).

    Overall, this is O(NlogN) as the preprocess sorting takes O(NlogN).

    Explanation

    Suppose we have entered elements 20 and 51 into a binary tree. We will then have 20 being the root, and 51 being the right child. To find the left child of 51 we need to find the first element in the array which has a value greater than 20, and less than 51. This value is given by our range minimum query applied to the range 20+1->51-1.

    We can therefore find the left and right children of all nodes faster than by inserting them into the binary tree in the natural way (only faster in a theoretical worst case - the other methods may well be faster for typical examples).

提交回复
热议问题