📜  检查两个给定的键序列是否构成相同的BST

📅  最后修改于: 2021-05-24 23:47:06             🧑  作者: Mango

给定两个数组,它们表示用于创建BST的两个键序列。想象一下,我们从每个数组中创建一个二叉搜索树(BST)。我们需要确定两个BST是否相同,而无需实际构建树。
例子:

Let the input arrays be a[] and b[]

Example 1:
a[] = {2, 4, 1, 3} will construct following tree.
   2
 /  \
1    4
    /
   3
b[] = {2, 4, 3, 1} will also also construct the same tree.
   2
 /  \
1    4
    /
   3 
So the output is "True"

Example 2:
a[] = {8, 3, 6, 1, 4, 7, 10, 14, 13}
b[] = {8, 10, 14, 3, 6, 4, 1, 7, 13}

They both construct the same following BST, so output is "True"
            8
         /    \
       3       10
     /  \        \
    1     6       14
        /   \     /
       4     7   13  

1)比较两个数组的大小。如果不相同,则返回false。
2)比较两个数组的第一个值。如果不相同,则返回false。
3)从每个给定的数组中创建两个列表,以使第一个列表包含的值小于相应数组的第一项。第二个列表包含更大的值。
4)递归检查第一个数组的第一个列表和第二个数组的第一个列表,第二个数组的第一个列表相同。

C++
// C++ program to check if given two arrays represent
// same BST.
 
#include 
using namespace std;
bool sameBSTs(vector aL1,
                            vector aL2)
{
    // Base cases
    if (aL1.size() != aL2.size())
        return false;
    if (aL1.size() == 0)
        return true;
    if (aL1[0] != aL2[0])
        return false;
 
    // Construct two lists from each input array. The first
    // list contains values smaller than first value, i.e.,
    // left subtree. And second list contains right subtree.
    vector aLLeft1 ;
    vector aLRight1 ;
    vector aLLeft2 ;
    vector aLRight2 ;
    for (int i = 1; i < aL1.size(); i++)
    {
        if (aL1[i] < aL1[0])
            aLLeft1.push_back(aL1[i]);
        else
            aLRight1.push_back(aL1[i]);
 
        if (aL2[i] < aL2[0])
            aLLeft2.push_back(aL2[i]);
        else
            aLRight2.push_back(aL2[i]);
    }
 
    // Recursively compare left and right
    // subtrees.
    return sameBSTs(aLLeft1, aLLeft2) &&
        sameBSTs(aLRight1, aLRight2);
}
 
// Driver code
int main()
{
    vector aL1;
    vector aL2;
    aL1.push_back(3);
    aL1.push_back(5);
    aL1.push_back(4);
    aL1.push_back(6);
    aL1.push_back(1);
    aL1.push_back(0);
    aL1.push_back(2);
     
    aL2.push_back(3);
    aL2.push_back(1);
    aL2.push_back(5);
    aL2.push_back(2);
    aL2.push_back(4);
    aL2.push_back(6);
    aL2.push_back(0);
     
    cout << ((sameBSTs(aL1, aL2))?"true":"false")<<"\n";
    return 0;
}
 
// This code is contributed by Arnab Kundu


Java
// Java program to check if given two arrays represent
// same BST.
import java.util.ArrayList;
import java.util.Arrays;
 
public class SameBST {
    static boolean sameBSTs(ArrayList aL1,
                            ArrayList aL2)
    {
        // Base cases
        if (aL1.size() != aL2.size())
            return false;
        if (aL1.size() == 0)
            return true;
        if (aL1.get(0) != aL2.get(0))
            return false;
 
        // Construct two lists from each input array. The first
        // list contains values smaller than first value, i.e.,
        // left subtree. And second list contains right subtree.
        ArrayList aLLeft1 = new ArrayList();
        ArrayList aLRight1 = new ArrayList();
        ArrayList aLLeft2 = new ArrayList();
        ArrayList aLRight2 = new ArrayList();
        for (int i = 1; i < aL1.size(); i++) {
            if (aL1.get(i) < aL1.get(0))
                aLLeft1.add(aL1.get(i));
            else
                aLRight1.add(aL1.get(i));
 
            if (aL2.get(i) < aL2.get(0))
                aLLeft2.add(aL2.get(i));
            else
                aLRight2.add(aL2.get(i));
        }
 
        // Recursively compare left and right
        // subtrees.
        return sameBSTs(aLLeft1, aLLeft2) &&
               sameBSTs(aLRight1, aLRight2);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        ArrayList aL1 =
                         new ArrayList(Arrays.
                           asList(3, 5, 4, 6, 1, 0, 2));
        ArrayList aL2 =
                         new ArrayList(Arrays.
                          asList(3, 1, 5, 2, 4, 6, 0));
 
        System.out.println(sameBSTs(aL1, aL2));
    }
}


Python3
# Python3 program to check if given two arrays represent
# same BST.
def sameBSTs(aL1, aL2):
     
    # Base cases
    if (len(aL1) != len(aL2)):
        return False
    if (len(aL1) == 0):
        return True
    if (aL1[0] != aL2[0]):
        return False
     
    # Construct two lists from each input array. The first
    # list contains values smaller than first value, i.e.,
    # left subtree. And second list contains right subtree.
    aLLeft1 = []
    aLRight1 = []
    aLLeft2 = []
    aLRight2 = []
    for i in range(1, len(aL1)):
        if (aL1[i] < aL1[0]):
            aLLeft1.append(aL1[i])
        else:
            aLRight1.append(aL1[i])
         
        if (aL2[i] < aL2[0]):
            aLLeft2.append(aL2[i])
        else:
            aLRight2.append(aL2[i])
     
    # Recursively compare left and right
    # subtrees.
    return sameBSTs(aLLeft1, aLLeft2) and sameBSTs(aLRight1, aLRight2)
 
# Driver code
aL1 = []
aL2 = []
aL1.append(3)
aL1.append(5)
aL1.append(4)
aL1.append(6)
aL1.append(1)
aL1.append(0)
aL1.append(2)
 
aL2.append(3)
aL2.append(1)
aL2.append(5)
aL2.append(2)
aL2.append(4)
aL2.append(6)
aL2.append(0)
 
if (sameBSTs(aL1, aL2)):
    print("true")
else:
    print("false")
 
# This code is contributed by shubhamsingh10


C#
// C# program to check if given
// two arrays represent same BST.
using System;
using System.Linq;
using System.Collections.Generic;
 
public class SameBST
{
    static bool sameBSTs(List aL1,
                            List aL2)
    {
        // Base cases
        if (aL1.Count != aL2.Count)
            return false;
        if (aL1.Count == 0)
            return true;
        if (aL1[0] != aL2[0])
            return false;
 
        // Construct two lists from each
        // input array. The first list contains
        // values smaller than first value, i.e.,
        // left subtree. And second list contains right subtree.
        List aLLeft1 = new List();
        List aLRight1 = new List();
        List aLLeft2 = new List();
        List aLRight2 = new List();
        for (int i = 1; i < aL1.Count; i++)
        {
            if (aL1[i] < aL1[0])
                aLLeft1.Add(aL1[i]);
            else
                aLRight1.Add(aL1[i]);
 
            if (aL2[i] < aL2[0])
                aLLeft2.Add(aL2[i]);
            else
                aLRight2.Add(aL2[i]);
        }
 
        // Recursively compare left and right
        // subtrees.
        return sameBSTs(aLLeft1, aLLeft2) &&
            sameBSTs(aLRight1, aLRight2);
    }
 
    // Driver code
    public static void Main()
    {
        int []arr1 = {3, 5, 4, 6, 1, 0, 2};
        List aL1 = arr1.ToList();
        int []arr2 = {3, 1, 5, 2, 4, 6, 0};
        List aL2 = arr2.ToList();
 
        Console.WriteLine(sameBSTs(aL1, aL2));
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


输出:
true

时间复杂度: O(n * n)
请参考下面的文章O(n)解决方案
在不构建树的情况下检查相同的BST