Problem:

  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

 Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. 

  Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

 Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

  The following figure shows an example of the binary search tree.

  For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

  A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

  To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2     y = NIL // parent of x
3     x = 'the root of T'
4     while x &ne; NIL
5         y = x // set the parent
6         if z.key < x.key
7             x = x.left // move to the left child
8         else 
9             x = x.right // move to the right child
10    z.p = y
11
12    if y == NIL // T is empty
13        'the root of T' = z
14    else if z.key < y.key
15        y.left = z // z is the left child of y
16    else 
17        y.right = z // z is the right child of y

  Write a program which performs the following operations to a binary search tree $T$.

insert  $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and  preorder tree walk respectively.

  You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

  In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

  For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print


Sample output:
 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Submission status: Time Limit Exceeded

Solution code:
import sys

class binarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, key):
        z = Node(key)
        y = None
        x = self.root
        while x:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right

        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def printBT(self):
        print inorderTreeWalk(self.root)
        print preorderTreeWalk(self.root)

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def inorderTreeWalk(node):
    if node:
        return inorderTreeWalk(node.left) + " " + str(node.key) + inorderTreeWalk(node.right)
    return ""

def preorderTreeWalk(node):
    if node:
        return " " + str(node.key) + preorderTreeWalk(node.left) + preorderTreeWalk(node.right)
    return ""

if __name__ == "__main__":
    lines = sys.stdin.readlines()

    bt = binarySearchTree()
    for i in range(1, int(lines[0]) + 1):
        if lines[i][0] == "i":
            bt.insert(int(lines[i].split()[1]))
        else:
            bt.printBT()

Submission status: Time Limit Exceeded

Solution code:
import sys

class binarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, key):
        z = Node(key)
        y = None
        x = self.root
        while x:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right

        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def printBT(self):
        print inorderTreeWalk(self.root)
        print preorderTreeWalk(self.root)

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def inorderTreeWalk(node):
    if node:
        return inorderTreeWalk(node.left) + " " + str(node.key) + inorderTreeWalk(node.right)
    return ""

def preorderTreeWalk(node):
    if node:
        return " " + str(node.key) + preorderTreeWalk(node.left) + preorderTreeWalk(node.right)
    return ""

if __name__ == "__main__":
    m = int(raw_input())
    bt = binarySearchTree()
    for i in range(m):
        line = raw_input()
        if line[0] == "i":
            bt.insert(int(line.split()[1]))
        else:
            bt.printBT()

Submission status: Time Limit Exceeded

Solution code:
import sys
import time

class Node:
    def __init__(self, key = None):
        self.key = key
        self.left = None
        self.right = None

def insert(key):
    global root
    z = Node(key)
    y = None
    x = root
    while x:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right

    if y is None:
        root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def inorderTreeWalk(node):
    if node:
        return inorderTreeWalk(node.left) + " " + str(node.key) + inorderTreeWalk(node.right)
    return ""

def preorderTreeWalk(node):
    if node:
        return " " + str(node.key) + preorderTreeWalk(node.left) + preorderTreeWalk(node.right)
    return ""

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    root = None
    for line in lines:
        if line[0] == "i":
            insert(int(line.split()[1]))
        else:
            print inorderTreeWalk(root)
            print preorderTreeWalk(root)

Submission status: Time Limit Exceeded

Solution code:
import sys
import time

class Node:
    def __init__(self, key = None):
        self.key = key
        self.left = None
        self.right = None

def insert(key):
    global root
    z = Node(key)
    y = None
    x = root
    while x:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right

    if y is None:
        root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def inorderTreeWalk(node):
    global In
    if node:
        inorderTreeWalk(node.left)
        In.append(str(node.key))
        inorderTreeWalk(node.right)

def preorderTreeWalk(node):
    global Pre
    if node:
        Pre.append(str(node.key))
        preorderTreeWalk(node.left)
        preorderTreeWalk(node.right)

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    root = None
    for line in lines:
        if line[0] == "i":
            insert(int(line.split()[1]))
        else:
            In = []
            Pre = []
            inorderTreeWalk(root)
            print " " + " ".join(map(str, In))
            preorderTreeWalk(root)
            print " " + " ".join(map(str, Pre))

Submission status: Time Limit Exceeded

Solution code:
import sys
import time

class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.left = None
        self.right = None

def insert(z):
    global root
    y = None
    x = root
    while x:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y is None:
        root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def inorderTreeWalk(node):
    global In
    if node:
        inorderTreeWalk(node.left)
        In.append(str(node.key))
        inorderTreeWalk(node.right)

def preorderTreeWalk(node):
    global Pre
    if node:
        Pre.append(str(node.key))
        preorderTreeWalk(node.left)
        preorderTreeWalk(node.right)

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    root = None
    for line in lines:
        if line[0] == "i":
            insert(Node(int(line.split()[1])))
        else:
            In = []
            Pre = []
            inorderTreeWalk(root)
            print " " + " ".join(map(str, In))
            preorderTreeWalk(root)
            print " " + " ".join(map(str, Pre))

Submission status: Time Limit Exceeded

Solution code:
class Node:
    def __init__(self,v):
        self.v = v
        self.left = None
        self.right = None

def inorder(n):
    if n != None:
        inorder(n.left)
        print n.v,
        inorder(n.right)

def preorder(n):
    if n != None:
        print n.v,
        preorder(n.left)
        preorder(n.right)

class BST:
    def __init__(self):
        self.root = None

    def insert(self,v):
        n = Node(v)
        x = self.root
        y = None
        while x != None:
            y = x
            if x.v > v:
                x = x.left
            else:
                x = x.right
        if y == None:
            self.root = n
        else:
            if y.v > v:
                y.left = n
            else:
                y.right = n
    def print_tree(self):
        print '',
        inorder(self.root)
        print
        print '',
        preorder(self.root)
        print


n = int(raw_input())
ops = []
for _ in range(n):
    ops.append(raw_input())

tree = BST()
for op in ops:
    if op[0] == 'i':
        num = op.split(' ')[1]
        num = int(num)
        tree.insert(num)
    else:
        tree.print_tree()

Submission status: Time Limit Exceeded

Solution code:
class Node:
  def __init__(self, label):
    self.label = label
    self.left = None
    self.right = None

class BinaryTree:
  def __init__(self):
    self.root = Node(None)

  # usage
  # btree.insert(btree.root, n)
  def insert(self, node, n):
    if node.label == None:
      node.label = n
    elif n < node.label:
      if node.left == None:
        node.left = Node(n)
      else:
        node.left = self.insert(node.left, n)
    else:
      if node.right == None:
        node.right = Node(n)
      else:
        node.right = self.insert(node.right, n)
    return node

  # usage
  # btree.printer(btree.root)
  def printer(self, node):
    labels = []
    if node.left != None:
      labels.extend(self.printer(node.left))
    labels.append(node.label)
    if node.right != None:
      labels.extend(self.printer(node.right))
    return labels

  # usage
  # btree.printer_c(btree.root)
  def printer_c(self, node):
    labels = []
    labels.append(node.label)
    if node.left != None:
      labels.extend(self.printer_c(node.left))
    if node.right != None:
      labels.extend(self.printer_c(node.right))
    return labels

btree = BinaryTree()
n = int(raw_input())
for _ in xrange(n):
  op = raw_input().split()
  if op[0] == "insert":
    btree.insert(btree.root, int(op[1]))
  elif op[0] == "print":
    print " "+" ".join(map(str, btree.printer(btree.root)))
    print " "+" ".join(map(str, btree.printer_c(btree.root)))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

output: in_order + pre_order
1 12 17 20 25 30 88
30 12 1 20 17 25 88

"""

import sys


class Node(object):
    def __init__(self, data):
        self.data = data
        self.left, self.right = None, None

    def insert(self, data):
        """
        insert data according to BST rules
        """
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)

        return None

    def pre_order(self, node):
        if node is not None:
            print('', node.data, end='')
            self.pre_order(node.left)
            self.pre_order(node.right)
        return None

    def in_order(self, node):
        if node is not None:
            self.in_order(node.left)
            print('', node.data, end='')
            self.in_order(node.right)
        return None


def action(command, content):
    if command.startswith('in'):
        tree_root.insert(data=int(content))

    if command.startswith('pr'):
        tree_root.in_order(node=tree_root)
        print('')
        tree_root.pre_order(node=tree_root)
        print('')

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    command_list = list(map(lambda x: x.split(), _input[1:]))
    # assert len(command_list) == array_length
    # print(array_length, *command_list)

    flag, tree_root = False, None
    for each in command_list:
        command, content = each[0], each[-1]
        if (not flag) and command.startswith('in'):
            tree_root = Node(data=int(content))
            flag = True
            continue
        action(command=command, content=content)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

output: in_order + pre_order
1 12 17 20 25 30 88
30 12 1 20 17 25 88

"""

import sys


class Node(object):
    def __init__(self, data):
        self.data = data
        self.left, self.right = None, None

    def insert(self, data):
        """
        insert data according to BST rules
        """
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)

        return None


def pre_order(node):
    if node is not None:
        print('', node.data, end='')
        pre_order(node.left)
        pre_order(node.right)
    return None


def in_order(node):
    if node is not None:
        in_order(node.left)
        print('', node.data, end='')
        in_order(node.right)
    return None


def action(command, content):
    if command.startswith('in'):
        tree_root.insert(data=int(content))

    if command.startswith('pr'):
        in_order(node=tree_root)
        print('')
        pre_order(node=tree_root)
        print('')

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    command_list = list(map(lambda x: x.split(), _input[1:]))
    # assert len(command_list) == array_length
    # print(array_length, *command_list)

    flag, tree_root = False, None
    for each in command_list:
        command, content = each[0], each[-1]
        if (not flag) and command.startswith('in'):
            tree_root = Node(data=int(content))
            flag = True
            continue
        action(command=command, content=content)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

output: in_order + pre_order
 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

"""

import sys


class Node(object):
    def __init__(self, data):
        self.data = data
        self.left, self.right = None, None

    def insert(self, data):
        """
        insert data according to BST rules
        """
        if data < self.data:
            if not self.left:
                self.left = Node(data)
            else:
                self.left.insert(data)
        # insert duplicate value to right
        else:
            if not self.right:
                self.right = Node(data)
            else:
                self.right.insert(data)

        return self.data


def pre_order(node):
    if node is not None:
        print('', node.data, end='')
        pre_order(node.left)
        pre_order(node.right)
    return None


def in_order(node):
    if node is not None:
        in_order(node.left)
        print('', node.data, end='')
        in_order(node.right)
    return None


def action(command, content):
    if command.startswith('in'):
        tree_root.insert(int(content))
    # print tree walk
    else:
        in_order(tree_root)
        print('')
        pre_order(tree_root)
        print('')

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    command_list = list(map(lambda x: x.split(), _input[1:]))
    # assert len(command_list) == array_length

    flag, tree_root = False, None
    for each in command_list:
        command, content = each[0], each[-1]
        if (not flag) and command.startswith('in'):
            tree_root = Node(data=int(content))
            flag = True
            continue
        action(command, content)

Submission status: Time Limit Exceeded

Solution code:
class BinaryTree:
    def __init__(self):
        self.root = None
    def b_insert(self,x):
        self.root = insert(self.root,x)
    def b_inorder(self):
        inorder(self.root)
    def b_preorder(self):
        preorder(self.root)
        
class Node:
    def __init__(self,x):
        self.data = x
        self.left = None
        self.right = None
            
def insert(node,x):
    if node is None:
        return Node(x)
    elif x == node.data:
        return node
    elif x < node.data:
        node.left = insert(node.left,x)
    else:
        node.right = insert(node.right,x)
    return node
def inorder(node):
    global count
    if node is None:
        return
    inorder(node.left)
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    inorder(node.right)
def preorder(node):
    global count
    if node is None:
        return
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    preorder(node.left)
    preorder(node.right)

length = int(input())
bfs = BinaryTree()
this_len = 0
for l in range(length):
    temp = input()
    if temp[0] == 'i':
        command,num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
        this_len += 1
    else:
        count = 0
        print("",end = " ")
        bfs.b_inorder()
        count = 0
        print("",end = " ")
        bfs.b_preorder()

Submission status: Time Limit Exceeded

Solution code:
class BinaryTree:
    def __init__(self):
        self.root = None
    def b_insert(self,x):
        self.root = insert(self.root,x)
    def b_inorder(self):
        inorder(self.root)
    def b_preorder(self):
        preorder(self.root)
        
class Node:
    def __init__(self,x):
        self.data = x
        self.left = None
        self.right = None
            
def insert(node,x):
    if node is None:
        return Node(x)
    elif x == node.data:
        return node
    elif x < node.data:
        node.left = insert(node.left,x)
    else:
        node.right = insert(node.right,x)
    return node
def inorder(node):
    global count
    # if node is None:
    #     return
    if node.left:
        inorder(node.left)
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    if node.right:
        inorder(node.right)
def preorder(node):
    global count
    # if node is None:
    #     return
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    if node.left:
        preorder(node.left)
    if node.right:
        preorder(node.right)

length = int(input())
bfs = BinaryTree()
this_len = 0
for l in range(length):
    temp = input()
    if temp[0] == 'i':
        command,num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
        this_len += 1
    else:
        count = 0
        print("",end = " ")
        bfs.b_inorder()
        count = 0
        print("",end = " ")
        bfs.b_preorder()

Submission status: Time Limit Exceeded

Solution code:
class BinaryTree:
    def __init__(self):
        self.root = None
    def b_insert(self,x):
        self.root = insert(self.root,x)
    def b_inorder(self):
        return inorder(self.root)
    def b_preorder(self):
        return preorder(self.root)
        
class Node:
    def __init__(self,x):
        self.data = x
        self.left = None
        self.right = None
            
def insert(node,x):
    if node is None:
        return Node(x)
    elif x == node.data:
        return node
    elif x < node.data:
        node.left = insert(node.left,x)
    else:
        node.right = insert(node.right,x)
    return node
def inorder(node):
    nodelist = []
    if node.left:
        nodelist += inorder(node.left)
    nodelist += [node.data]
    if node.right:
        nodelist += inorder(node.right)
    return nodelist
def preorder(node):
    nodelist = [node.data]
    if node.left:
        nodelist += preorder(node.left)
    if node.right:
        nodelist += preorder(node.right)
    return nodelist

length = int(input())
bfs = BinaryTree()
for l in range(length):
    temp = input()
    if temp[0] == 'i':
        command,num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
    else:
        count = 0
        print("",end=" ")
        print(*bfs.b_inorder())
        print("",end=" ")
        print(*bfs.b_preorder())

Submission status: Time Limit Exceeded

Solution code:
import sys
class BinaryTree:
    def __init__(self):
        self.root = None
    def b_insert(self,x):
        self.root = insert(self.root,x)
    def b_inorder(self):
        return inorder(self.root)
    def b_preorder(self):
        return preorder(self.root)
        
class Node:
    def __init__(self,x):
        self.data = x
        self.left = None
        self.right = None
            
def insert(node,x):
    if node is None:
        return Node(x)
    elif x == node.data:
        return node
    elif x < node.data:
        node.left = insert(node.left,x)
    else:
        node.right = insert(node.right,x)
    return node
def inorder(node):
    nodelist = []
    if node.left:
        nodelist += inorder(node.left)
    nodelist += [node.data]
    if node.right:
        nodelist += inorder(node.right)
    return nodelist
def preorder(node):
    nodelist = [node.data]
    if node.left:
        nodelist += preorder(node.left)
    if node.right:
        nodelist += preorder(node.right)
    return nodelist

line = sys.stdin.readline()
bfs = BinaryTree()

for temp in sys.stdin:
    if temp[0] == 'i':
        command,num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
    else:
        print("",end=" ")
        print(*bfs.b_inorder())
        print("",end=" ")
        print(*bfs.b_preorder())

Submission status: Time Limit Exceeded

Solution code:
import sys

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
    
    def insert(node, x):
        if node == None:
            return Node(x)
        elif x == node.data:
            return node
        elif x < node.data:
            node.left = Node.insert(node.left, x)
        else:
            node.right = Node.insert(node.right, x)
        return node
    def print1(node):
        if node.left != None:
            Node.print1(node.left)
        print("",node.data,  end="")
        if node.right != None:
            Node.print1(node.right)
    def print2(node):
        print("",node.data,  end="")
        if node.left != None:
            Node.print2(node.left)
        if node.right != None:
            Node.print2(node.right)
        
class BinaryTree:
    def __init__(self):
        self.root = None
    
    def insert(self, x):
        self.root = Node.insert(self.root, x)

    def print_tree(self):
        Node.print1(self.root)
        print()
        Node.print2(self.root)
        print()

def main():
    T = BinaryTree()
    m = int(sys.stdin.readline())
    for i in range(m):
        s = sys.stdin.readline().strip()
        if(s == "print"):
            T.print_tree()
        else:
            z = int(s.split()[1])
            #print(z)
            T.insert(z)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
    
    def insert(node, x):
        if node == None:
            return Node(x)
        elif x == node.data:
            return node
        elif x < node.data:
            node.left = Node.insert(node.left, x)
        else:
            node.right = Node.insert(node.right, x)
        return node
    def print1(node):
        if node.left != None:
            Node.print1(node.left)
        print("",node.data,  end="")
        if node.right != None:
            Node.print1(node.right)
    def print2(node):
        print("",node.data,  end="")
        if node.left != None:
            Node.print2(node.left)
        if node.right != None:
            Node.print2(node.right)
        
class BinaryTree:
    def __init__(self):
        self.root = None
    
    def insert(self, x):
        self.root = Node.insert(self.root, x)

    def print_tree(self):
        Node.print1(self.root)
        print()
        Node.print2(self.root)
        print()

def main():
    T = BinaryTree()
    m = int(sys.stdin.readline())
    for i in range(m):
        s = sys.stdin.readline().strip()
        if(s == "print"):
            T.print_tree()
        else:
            z = int(s.split()[1])
            T.insert(z)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
    
    def insert(node, x):
        if node == None:
            return Node(x)
        elif x == node.data:
            return node
        elif x < node.data:
            node.left = Node.insert(node.left, x)
        else:
            node.right = Node.insert(node.right, x)
        return node
    
    def find(node, x):
        if node.data == x:
            return True
        elif node.left != None and node.data > x:
            return Node.find(node.left, x)
        elif node.right != None and node.data < x:
            return Node.find(node.right, x)
        else:
            return False
        
    def delete(node, x):
        if node.data == x:
            if (node.left == None) and (node.right == None):
                return None
            elif node.left == None:
                return node.right
            elif node.right == None:
                return node.left
            else:
                #????????????
                node.data = Node.serch_min(node.right)
                node.right = Node.delete_min(node.right)
                return node
        elif node.data > x:
            node.left =  Node.delete(node.left, x)
        else:
            node.right =  Node.delete(node.right, x)
        return node
        
    def serch_min(node):
        if node.left != None:
            return Node.serch_min(node.left)
        else:
            return node.data
    
    def delete_min(node):
        if node.left == None:
            return node.right
        else:
            node.left = Node.delete_min(node.left)
                
        
    def inorder_print(node):
        if node.left != None:
            Node.inorder_print(node.left)
        print("",node.data,  end="")
        if node.right != None:
            Node.inorder_print(node.right)
    def preorder_print(node):
        print("",node.data,  end="")
        if node.left != None:
            Node.preorder_print(node.left)
        if node.right != None:
            Node.preorder_print(node.right)
        
class BinaryTree:
    def __init__(self):
        self.root = None
    
    def insert(self, x):
        self.root = Node.insert(self.root, x)

    def find(self, x):
        if Node.find(self.root, x):
            print("yes")
        else:
            print("no")
            
    def delete(self, x):
        self.root = Node.delete(self.root, x)
        
    def print_tree(self):
        Node.inorder_print(self.root)
        print()
        Node.preorder_print(self.root)
        print()

def main():
    T = BinaryTree()
    m = int(sys.stdin.readline())
    for i in range(m):
        s = sys.stdin.readline().strip()
        if(s == "print"):
            T.print_tree()
        elif s.split()[0] == "find":
            T.find(int(s.split()[1]))
        elif s.split()[0] == "delete":
            T.delete(int(s.split()[1]))
        else:
            z = int(s.split()[1])
            T.insert(z)

if __name__ == "__main__":
    main()