📌  相关文章
📜  检查两个BST是否包含相同的元素集

📅  最后修改于: 2021-05-24 22:31:10             🧑  作者: Mango

给定两个由唯一的正元素组成的二叉搜索树,我们必须检查两个BST是否包含相同的集合或元素。
注意:两个给定的BST的结构可以不同。
例如,
9(5)

上面的两个BST包含相同的元素集{5、10、12、15、20、25}

方法1 :最简单的方法是遍历第一棵树并将其元素存储在列表或数组中。现在,遍历第二棵树并同时检查列表中是否存在当前元素。如果是,则将列表中的元素标记为否,然后检查其他元素,否则,立即终止遍历并打印No。如果第二棵树的所有元素都存在于列表中并标记为负,则最后遍历该元素。列表以检查是否还有任何非负元素。如果是,则意味着第一棵树具有一些额外的元素,否则,这两个树都包含相同的元素集。

时间复杂度:O(n * n),其中n是BST中的节点数。
辅助空间:O(n)。

方法2 :此方法是上述方法的优化。如果仔细观察,我们会发现在上述方法中,在列表中搜索元素需要花费线性时间。我们可以使用哈希图而不是列表来优化此操作,使其在恒定时间内完成。我们将两棵树的元素插入不同的哈希集中。最后,我们比较两个哈希集是否包含相同的元素。

以下是上述方法的完整实现:

C++
// CPP program to check if two BSTs contains
// same set of elements
#include
using namespace std;
  
// BST Node
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
  
// Utility function to create new Node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->data = val;
    temp->left = temp->right = NULL; 
    return temp;
}
  
// function to insert elements of the 
// tree to map m
void insertToHash(Node* root, unordered_set &s)
{
    if (!root)
        return;
    insertToHash(root->left, s);
    s.insert(root->data);
    insertToHash(root->right, s);
}
  
// function to check if the two BSTs contain
// same set  of elements
bool checkBSTs(Node* root1, Node* root2)
{ 
    // Base cases 
    if (!root1 && !root2) 
        return true;
    if ((root1 && !root2) || (!root1 && root2))
        return false;
          
    // Create two hash sets and store 
    // elements both BSTs in them.
    unordered_set s1, s2;
    insertToHash(root1, s1);
    insertToHash(root2, s2);
  
    // Return true if both hash sets 
    // contain same elements.
    return (s1 == s2);
}
  
// Driver program to check above functions
int main()
{ 
    // First BST
    Node* root1 = newNode(15);
    root1->left = newNode(10);
    root1->right = newNode(20);
    root1->left->left = newNode(5);
    root1->left->right = newNode(12);
    root1->right->right = newNode(25);
      
    // Second BST
    Node* root2 = newNode(15);
    root2->left = newNode(12);
    root2->right = newNode(20);
    root2->left->left = newNode(5);
    root2->left->left->right = newNode(10);
    root2->right->right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        cout << "YES";
    else
        cout << "NO";
    return 0;        
}


Java
// JAVA program to check if two BSTs contains
// same set of elements
import java.util.*;
  
class GFG
{
  
// BST Node
static class Node
{
    int data;
    Node left;
    Node right;
};
  
// Utility function to create new Node
static Node newNode(int val)
{
    Node temp = new Node();
    temp.data = val;
    temp.left = temp.right = null; 
    return temp;
}
  
// function to insert elements of the 
// tree to map m
static void insertToHash(Node root, HashSet s)
{
    if (root == null)
        return;
    insertToHash(root.left, s);
    s.add(root.data);
    insertToHash(root.right, s);
}
  
// function to check if the two BSTs contain
// same set of elements
static boolean checkBSTs(Node root1, Node root2)
{ 
    // Base cases 
    if (root1 != null && root2 != null) 
        return true;
    if ((root1 == null && root2 != null) || (root1 != null && root2 == null))
        return false;
          
    // Create two hash sets and store 
    // elements both BSTs in them.
    HashSet s1 = new HashSet();
    HashSet s2 = new HashSet();
    insertToHash(root1, s1);
    insertToHash(root2, s2);
      
    // Return true if both hash sets 
    // contain same elements.
    return (s1.equals(s2));
}
  
// Driver program to check above functions
public static void main(String[] args)
{ 
    // First BST
    Node root1 = newNode(15);
    root1.left = newNode(10);
    root1.right = newNode(20);
    root1.left.left = newNode(5);
    root1.left.right = newNode(12);
    root1.right.right = newNode(25);
      
    // Second BST
    Node root2 = newNode(15);
    root2.left = newNode(12);
    root2.right = newNode(20);
    root2.left.left = newNode(5);
    root2.left.left.right = newNode(10);
    root2.right.right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        System.out.print("YES");
    else
        System.out.print("NO");
}     
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program to check if two BSTs contains
# same set of elements
  
# BST Node
class Node:
    def __init__(self):
        self.val = 0
        self.left = None
        self.right = None
  
# Utility function to create Node
def Node_(val1):
  
    temp = Node()
    temp.val = val1
    temp.left = temp.right = None
    return temp
  
s = {}
  
# function to insert elements of the 
# tree to map m
def insertToHash(root):
  
    if (root == None):
        return
    insertToHash(root.left)
    s.add(root.data)
    insertToHash(root.right)
  
# function to check if the two BSTs contain
# same set of elements
def checkBSTs(root1, root2):
  
    # Base cases 
    if (root1 != None and root2 != None) :
        return True
    if ((root1 == None and root2 != None) or 
        (root1 != None and root2 == None)):
        return False
          
    # Create two hash sets and store 
    # elements both BSTs in them.
    s1 = {}
    s2 = {}
    s = s1
    insertToHash(root1)
    s1 = s
    s = s2
    insertToHash(root2)
    s2 = s
      
    # Return True if both hash sets 
    # contain same elements.
    return (s1 == (s2))
  
# Driver code
  
# First BST
root1 = Node_(15)
root1.left = Node_(10)
root1.right = Node_(20)
root1.left.left = Node_(5)
root1.left.right = Node_(12)
root1.right.right = Node_(25)
      
# Second BST
root2 = Node_(15)
root2.left = Node_(12)
root2.right = Node_(20)
root2.left.left = Node_(5)
root2.left.left.right = Node_(10)
root2.right.right = Node_(25)
      
# check if two BSTs have same set of elements
if (checkBSTs(root1, root2)):
    print("YES")
else:
    print("NO")
      
# This code is contributed by Arnab Kundu


C#
// C# program to check if two BSTs contains
// same set of elements
using System;
using System.Collections.Generic;
  
class GFG
{
  
// BST Node
class Node
{
    public int data;
    public Node left;
    public Node right;
};
  
// Utility function to create new Node
static Node newNode(int val)
{
    Node temp = new Node();
    temp.data = val;
    temp.left = temp.right = null; 
    return temp;
}
  
// function to insert elements of the 
// tree to map m
static void insertToHash(Node root, 
                         HashSet s)
{
    if (root == null)
        return;
    insertToHash(root.left, s);
    s.Add(root.data);
    insertToHash(root.right, s);
}
  
// function to check if the two BSTs contain
// same set of elements
static bool checkBSTs(Node root1, Node root2)
{ 
    // Base cases 
    if (root1 != null && root2 != null) 
        return true;
    if ((root1 == null && root2 != null) || 
        (root1 != null && root2 == null))
        return false;
          
    // Create two hash sets and store 
    // elements both BSTs in them.
    HashSet s1 = new HashSet();
    HashSet s2 = new HashSet();
    insertToHash(root1, s1);
    insertToHash(root2, s2);
      
    // Return true if both hash sets 
    // contain same elements.
    return (s1.Equals(s2));
}
  
// Driver Code
public static void Main(String[] args)
{ 
    // First BST
    Node root1 = newNode(15);
    root1.left = newNode(10);
    root1.right = newNode(20);
    root1.left.left = newNode(5);
    root1.left.right = newNode(12);
    root1.right.right = newNode(25);
      
    // Second BST
    Node root2 = newNode(15);
    root2.left = newNode(12);
    root2.right = newNode(20);
    root2.left.left = newNode(5);
    root2.left.left.right = newNode(10);
    root2.right.right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        Console.Write("YES");
    else
        Console.Write("NO");
}     
}
  
// This code is contributed by PrinciRaj1992


C++
// CPP program to check if two BSTs contains
// same set of elements
#include
using namespace std;
  
// BST Node
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
  
// Utility function to create new Node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->data = val;
    temp->left = temp->right = NULL; 
    return temp;
}
  
// function to insert elements of the 
// tree to map m
void storeInorder(Node* root, vector &v)
{
    if (!root)
        return;
    storeInorder(root->left, v);
    v.push_back(root->data);
    storeInorder(root->right, v);
}
  
// function to check if the two BSTs contain
// same set  of elements
bool checkBSTs(Node* root1, Node* root2)
{ 
    // Base cases 
    if (!root1 && !root2) 
        return true;
    if ((root1 && !root2) || (!root1 && root2))
        return false;
          
    // Create two vectors and store 
    // inorder traversals of both BSTs 
    // in them.
    vector v1, v2;
    storeInorder(root1, v1);
    storeInorder(root2, v2);
  
    // Return true if both vectors are
    // identical
    return (v1 == v2);
}
  
// Driver program to check above functions
int main()
{ 
    // First BST
    Node* root1 = newNode(15);
    root1->left = newNode(10);
    root1->right = newNode(20);
    root1->left->left = newNode(5);
    root1->left->right = newNode(12);
    root1->right->right = newNode(25);
      
    // Second BST
    Node* root2 = newNode(15);
    root2->left = newNode(12);
    root2->right = newNode(20);
    root2->left->left = newNode(5);
    root2->left->left->right = newNode(10);
    root2->right->right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        cout << "YES";
    else
        cout << "NO";
    return 0;        
}


Java
// Java program to check if two BSTs 
// contain same set of elements
import java.util.*;
  
class GFG
{
  
// BST Node
static class Node
{
    int data;
    Node left;
    Node right;
};
  
// Utility function to create new Node
static Node newNode(int val)
{
    Node temp = new Node();
    temp.data = val;
    temp.left = temp.right = null; 
    return temp;
}
  
// function to insert elements  
// of the tree to map m
static void storeInorder(Node root,
                         Vector v)
{
    if (root == null)
        return;
    storeInorder(root.left, v);
    v.add(root.data);
    storeInorder(root.right, v);
}
  
// function to check if the two BSTs 
// contain same set of elements
static boolean checkBSTs(Node root1, Node root2)
{ 
    // Base cases 
    if (root1 != null && root2 != null) 
        return true;
    if ((root1 == null && root2 != null) || 
        (root1 != null && root2 == null))
        return false;
          
    // Create two vectors and store 
    // inorder traversals of both BSTs 
    // in them.
    Vector v1 = new Vector();
    Vector v2 = new Vector();
    storeInorder(root1, v1);
    storeInorder(root2, v2);
  
    // Return true if both vectors are
    // identical
    return (v1 == v2);
}
  
// Driver Code
public static void main(String[] args)
{ 
    // First BST
    Node root1 = newNode(15);
    root1.left = newNode(10);
    root1.right = newNode(20);
    root1.left.left = newNode(5);
    root1.left.right = newNode(12);
    root1.right.right = newNode(25);
      
    // Second BST
    Node root2 = newNode(15);
    root2.left = newNode(12);
    root2.right = newNode(20);
    root2.left.left = newNode(5);
    root2.left.left.right = newNode(10);
    root2.right.right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        System.out.print("YES");
    else
        System.out.print("NO");
}     
}
  
// This code is contributed by Rajput-Ji


Python3
# Python3 program to check if two BSTs contains
# same set of elements
  
# BST Node
class Node:
    def __init__(self):
        self.val = 0
        self.left = None
        self.right = None
  
# Utility function to create Node
def Node_(val1):
  
    temp = Node()
    temp.val = val1
    temp.left = temp.right = None
    return temp
  
v = []
  
# function to insert elements of the 
# tree to map m
def storeInorder(root):
  
    if (root == None):
        return
    storeInorder(root.left)
    v.append(root.data)
    storeInorder(root.right)
  
# function to check if the two BSTs contain
# same set of elements
def checkBSTs(root1, root2):
  
    # Base cases 
    if (root1 != None and root2 != None) :
        return True
    if ((root1 == None and root2 != None) or \
        (root1 != None and root2 == None)):
        return False
          
    # Create two hash sets and store 
    # elements both BSTs in them.
    v1 = []
    v2 = []
    v = v1
    storeInorder(root1)
    v1 = v
    v = v2
    storeInorder(root2)
    v2 = v
      
    # Return True if both hash sets 
    # contain same elements.
    return (v1 == v2)
  
# Driver code
  
# First BST
root1 = Node_(15)
root1.left = Node_(10)
root1.right = Node_(20)
root1.left.left = Node_(5)
root1.left.right = Node_(12)
root1.right.right = Node_(25)
      
# Second BST
root2 = Node_(15)
root2.left = Node_(12)
root2.right = Node_(20)
root2.left.left = Node_(5)
root2.left.left.right = Node_(10)
root2.right.right = Node_(25)
      
# check if two BSTs have same set of elements
if (checkBSTs(root1, root2)):
    print("YES")
else:
    print("NO")
      
# This code is contributed by SHUBHAMSINGH10


C#
// C# program to check if two BSTs 
// contain same set of elements
using System;
using System.Collections.Generic;
  
class GFG
{
  
// BST Node
class Node
{
    public int data;
    public Node left;
    public Node right;
};
  
// Utility function to create new Node
static Node newNode(int val)
{
    Node temp = new Node();
    temp.data = val;
    temp.left = temp.right = null; 
    return temp;
}
  
// function to insert elements 
// of the tree to map m
static void storeInorder(Node root,
                         List v)
{
    if (root == null)
        return;
    storeInorder(root.left, v);
    v.Add(root.data);
    storeInorder(root.right, v);
}
  
// function to check if the two BSTs 
// contain same set of elements
static bool checkBSTs(Node root1, 
                      Node root2)
{ 
    // Base cases 
    if (root1 != null && root2 != null) 
        return true;
    if ((root1 == null && root2 != null) || 
        (root1 != null && root2 == null))
        return false;
          
    // Create two vectors and store 
    // inorder traversals of both BSTs 
    // in them.
    List v1 = new List();
    List v2 = new List();
    storeInorder(root1, v1);
    storeInorder(root2, v2);
  
    // Return true if both vectors are
    // identical
    return (v1 == v2);
}
  
// Driver Code
public static void Main(String[] args)
{ 
    // First BST
    Node root1 = newNode(15);
    root1.left = newNode(10);
    root1.right = newNode(20);
    root1.left.left = newNode(5);
    root1.left.right = newNode(12);
    root1.right.right = newNode(25);
      
    // Second BST
    Node root2 = newNode(15);
    root2.left = newNode(12);
    root2.right = newNode(20);
    root2.left.left = newNode(5);
    root2.left.left.right = newNode(10);
    root2.right.right = newNode(25);
      
    // check if two BSTs have 
    // same set of elements
    if (checkBSTs(root1, root2))
        Console.Write("YES");
    else
        Console.Write("NO");
}     
}
  
// This code is contributed by Rajput-Ji


输出:

YES

时间复杂度:O(n),其中n是树中的节点数。
辅助空间:O(n)。

方法3 :我们知道BST的一个有趣特性,即BST的有序遍历会生成一个排序数组。因此,我们可以对两个BST进行有序遍历并生成两个数组,最后可以比较这两个数组。如果两个数组相同,则BST具有相同的元素集,否则不相同。

C++

// CPP program to check if two BSTs contains
// same set of elements
#include
using namespace std;
  
// BST Node
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
  
// Utility function to create new Node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->data = val;
    temp->left = temp->right = NULL; 
    return temp;
}
  
// function to insert elements of the 
// tree to map m
void storeInorder(Node* root, vector &v)
{
    if (!root)
        return;
    storeInorder(root->left, v);
    v.push_back(root->data);
    storeInorder(root->right, v);
}
  
// function to check if the two BSTs contain
// same set  of elements
bool checkBSTs(Node* root1, Node* root2)
{ 
    // Base cases 
    if (!root1 && !root2) 
        return true;
    if ((root1 && !root2) || (!root1 && root2))
        return false;
          
    // Create two vectors and store 
    // inorder traversals of both BSTs 
    // in them.
    vector v1, v2;
    storeInorder(root1, v1);
    storeInorder(root2, v2);
  
    // Return true if both vectors are
    // identical
    return (v1 == v2);
}
  
// Driver program to check above functions
int main()
{ 
    // First BST
    Node* root1 = newNode(15);
    root1->left = newNode(10);
    root1->right = newNode(20);
    root1->left->left = newNode(5);
    root1->left->right = newNode(12);
    root1->right->right = newNode(25);
      
    // Second BST
    Node* root2 = newNode(15);
    root2->left = newNode(12);
    root2->right = newNode(20);
    root2->left->left = newNode(5);
    root2->left->left->right = newNode(10);
    root2->right->right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        cout << "YES";
    else
        cout << "NO";
    return 0;        
}

Java

// Java program to check if two BSTs 
// contain same set of elements
import java.util.*;
  
class GFG
{
  
// BST Node
static class Node
{
    int data;
    Node left;
    Node right;
};
  
// Utility function to create new Node
static Node newNode(int val)
{
    Node temp = new Node();
    temp.data = val;
    temp.left = temp.right = null; 
    return temp;
}
  
// function to insert elements  
// of the tree to map m
static void storeInorder(Node root,
                         Vector v)
{
    if (root == null)
        return;
    storeInorder(root.left, v);
    v.add(root.data);
    storeInorder(root.right, v);
}
  
// function to check if the two BSTs 
// contain same set of elements
static boolean checkBSTs(Node root1, Node root2)
{ 
    // Base cases 
    if (root1 != null && root2 != null) 
        return true;
    if ((root1 == null && root2 != null) || 
        (root1 != null && root2 == null))
        return false;
          
    // Create two vectors and store 
    // inorder traversals of both BSTs 
    // in them.
    Vector v1 = new Vector();
    Vector v2 = new Vector();
    storeInorder(root1, v1);
    storeInorder(root2, v2);
  
    // Return true if both vectors are
    // identical
    return (v1 == v2);
}
  
// Driver Code
public static void main(String[] args)
{ 
    // First BST
    Node root1 = newNode(15);
    root1.left = newNode(10);
    root1.right = newNode(20);
    root1.left.left = newNode(5);
    root1.left.right = newNode(12);
    root1.right.right = newNode(25);
      
    // Second BST
    Node root2 = newNode(15);
    root2.left = newNode(12);
    root2.right = newNode(20);
    root2.left.left = newNode(5);
    root2.left.left.right = newNode(10);
    root2.right.right = newNode(25);
      
    // check if two BSTs have same set of elements
    if (checkBSTs(root1, root2))
        System.out.print("YES");
    else
        System.out.print("NO");
}     
}
  
// This code is contributed by Rajput-Ji

Python3

# Python3 program to check if two BSTs contains
# same set of elements
  
# BST Node
class Node:
    def __init__(self):
        self.val = 0
        self.left = None
        self.right = None
  
# Utility function to create Node
def Node_(val1):
  
    temp = Node()
    temp.val = val1
    temp.left = temp.right = None
    return temp
  
v = []
  
# function to insert elements of the 
# tree to map m
def storeInorder(root):
  
    if (root == None):
        return
    storeInorder(root.left)
    v.append(root.data)
    storeInorder(root.right)
  
# function to check if the two BSTs contain
# same set of elements
def checkBSTs(root1, root2):
  
    # Base cases 
    if (root1 != None and root2 != None) :
        return True
    if ((root1 == None and root2 != None) or \
        (root1 != None and root2 == None)):
        return False
          
    # Create two hash sets and store 
    # elements both BSTs in them.
    v1 = []
    v2 = []
    v = v1
    storeInorder(root1)
    v1 = v
    v = v2
    storeInorder(root2)
    v2 = v
      
    # Return True if both hash sets 
    # contain same elements.
    return (v1 == v2)
  
# Driver code
  
# First BST
root1 = Node_(15)
root1.left = Node_(10)
root1.right = Node_(20)
root1.left.left = Node_(5)
root1.left.right = Node_(12)
root1.right.right = Node_(25)
      
# Second BST
root2 = Node_(15)
root2.left = Node_(12)
root2.right = Node_(20)
root2.left.left = Node_(5)
root2.left.left.right = Node_(10)
root2.right.right = Node_(25)
      
# check if two BSTs have same set of elements
if (checkBSTs(root1, root2)):
    print("YES")
else:
    print("NO")
      
# This code is contributed by SHUBHAMSINGH10

C#

// C# program to check if two BSTs 
// contain same set of elements
using System;
using System.Collections.Generic;
  
class GFG
{
  
// BST Node
class Node
{
    public int data;
    public Node left;
    public Node right;
};
  
// Utility function to create new Node
static Node newNode(int val)
{
    Node temp = new Node();
    temp.data = val;
    temp.left = temp.right = null; 
    return temp;
}
  
// function to insert elements 
// of the tree to map m
static void storeInorder(Node root,
                         List v)
{
    if (root == null)
        return;
    storeInorder(root.left, v);
    v.Add(root.data);
    storeInorder(root.right, v);
}
  
// function to check if the two BSTs 
// contain same set of elements
static bool checkBSTs(Node root1, 
                      Node root2)
{ 
    // Base cases 
    if (root1 != null && root2 != null) 
        return true;
    if ((root1 == null && root2 != null) || 
        (root1 != null && root2 == null))
        return false;
          
    // Create two vectors and store 
    // inorder traversals of both BSTs 
    // in them.
    List v1 = new List();
    List v2 = new List();
    storeInorder(root1, v1);
    storeInorder(root2, v2);
  
    // Return true if both vectors are
    // identical
    return (v1 == v2);
}
  
// Driver Code
public static void Main(String[] args)
{ 
    // First BST
    Node root1 = newNode(15);
    root1.left = newNode(10);
    root1.right = newNode(20);
    root1.left.left = newNode(5);
    root1.left.right = newNode(12);
    root1.right.right = newNode(25);
      
    // Second BST
    Node root2 = newNode(15);
    root2.left = newNode(12);
    root2.right = newNode(20);
    root2.left.left = newNode(5);
    root2.left.left.right = newNode(10);
    root2.right.right = newNode(25);
      
    // check if two BSTs have 
    // same set of elements
    if (checkBSTs(root1, root2))
        Console.Write("YES");
    else
        Console.Write("NO");
}     
}
  
// This code is contributed by Rajput-Ji

输出:

YES

时间复杂度:O(n)。
辅助空间:O(n)。