Binary Search Tree 1#4146

Binary Search Tree 1 (Editorial)

Simulate the specified operations using a set data structure.

Algorithm implementation

Declare a set .

set<int> s;

Read the input data.

while (cin >> op >> x)
{

Insert an element into the set.

  if (op == "insert") s.insert(x); else

Remove an element from the set if it exists there.

  if (op == "delete") s.erase(x);  else
  {

Check if an element exists in the set.

    if (s.find(x) != s.end()) printf("true\n");
    else printf("false\n");
  }
}

Java implementation

import java.util.*;

public class Main
{
  public static void main(String []args)
  {
    Scanner con = new Scanner(System.in);
    TreeSet<Integer> s = new TreeSet<Integer>();
    
    while(con.hasNext())
    {
      String c = con.next();
      int x = con.nextInt();
      if (c.charAt(0) == 'i') s.add(x); else
      if (c.charAt(0) == 'd') s.remove(x); else
      {
        if (s.contains(x))
          System.out.println("true");
        else
          System.out.println("false");
      }
    }
    con.close();
  }
} 

Python implementation

import sys

Declare a set.

s = set()

Read the input data.

for line in sys.stdin:
  op, x = line.split()
  x = int(x)

Insert an element into the set.

 if op == "insert":
    s.add(x)

Remove an element from the set if it exists there.

  elif op == "delete":
    s.discard(x)
  else:

Check if an element exists in the set.

    if x in s:
      print("true")
    else:
      print("false")