Problem:

Binary Search Tree II

Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.

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

  
find $k$: Report whether $T$ has a node containing $k$. 

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

Input

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

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

  In addition, 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

10
insert 30
insert 88
insert 12
insert 1
insert 20
find 12
insert 17
insert 25
find 16
print

Sample Output 1

yes
no
 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:
10
insert 30
insert 88
insert 12
insert 1
insert 20
find 12
insert 17
insert 25
find 16
print


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

Submission status: Accepted

Solution code:
import sys

class Node:
    __slots__ = ['key', 'left', 'right']
    def __init__(self, key):
        self.key = key
        self.left = self.right = None

root = None

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

def find(target):
    result = root
    while result and target != result.key:
        result = result.left if target < result.key else result.right
    return result is None

def inorder(node):
    return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else ''
def preorder(node):
    return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else ''

input()
for e in sys.stdin:
    if e[0] == 'i': insert(int(e[7:]))
    elif e[0] == 'f': print(['yes','no'][find(int(e[5:]))])
    else: print(inorder(root)); print(preorder(root))

Submission status: Accepted

Solution code:
class node:
    def __init__(self):
        self.parent = None
        self.left = None
        self.right = None
        self.key = None
        
class btree:
    def __init__(self):
        self.root = None
        
    def insert(self, v):
        y = None
        x = self.root
        z = node()
        z.key = v
        
        while x is not None:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        
        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
    
    def find(self, v):
        x = self.root
        z = node()
        z.key = v
        
        find_flg = 0
        while x is not None:
            if x.key == z.key:
                find_flg = 1
                break

            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        
        if find_flg:
            print('yes')
        else:
            print('no')
    

    def print_tree(self):
        def inorder(nd):
            if nd.left is not None:
                inorder(nd.left)
            print(' %i'%nd.key, end='')
            if nd.right is not None:
                inorder(nd.right)
        
        def preorder(nd):
            print(' %i'%nd.key, end='')
            if nd.left is not None:
                preorder(nd.left)
            if nd.right is not None:
                preorder(nd.right)
                
        inorder(self.root)
        print()
        preorder(self.root)
        print()
        
n = int(input())

bt = btree()

for i in range(n):
    inp = input()
    if inp.split()[0]=='insert':
        bt.insert(int(inp.split()[1]))
    elif inp.split()[0]=='find':
        bt.find(int(inp.split()[1]))
    else:
        bt.print_tree()

Submission status: Accepted

Solution code:
n = int(input())
COM = [list(input().split()) for _ in range(n)]

class Node:
    def __init__(self,data):
        self.data = data #int
        self.left = None #Node
        self.right = None #Node
        self.parent = None #Node

    def inorder(self,List):
        if self.data != None:
            if self.left != None:
                self.left.inorder(List)
            List.append(self.data)
            if self.right != None:
                self.right.inorder(List)
        return List

    def preorder(self,List):
        if self.data != None:
            List.append(self.data)
            if self.left != None:
                self.left.preorder(List)
            if self.right != None:
                self.right.preorder(List)
        return List

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

    def insert(self,z):
        y = None
        x = self.root
        while x != None:
            y = x
            if z.data < x.data:
                x = x.left
            else:
                x = x.right
        z.parent = y
        if y == None:
            self.root = z
        elif z.data < y.data:
            y.left = z
        else:
            y.right = z

    def find(self,data):
        pt = self.root
        flag = 0
        while pt != None:
            if pt.data == data:
                flag = 1
                print("yes")
                break
            elif pt.data > data:
                pt = pt.left
            else:
                pt = pt.right
        if flag == 0:
            print("no")

    def print(self):
        print(""," ".join(map(str,self.root.inorder([])))) #なぜかjoinを使ったら速くなった
        print(""," ".join(map(str,self.root.preorder([]))))

btree = BTree()
cnt = 0
for i in range(n):
    if COM[i][0] == "insert":
        node = Node(int(COM[i][1]))
        btree.insert(node)
        cnt += 1
    elif COM[i][0] == "find":
        btree.find(int(COM[i][1]))
    else:
        btree.print()

Submission status: Accepted

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

    def insert(self, key):
        new = Node(key)
        parent = None
        current = self.root
        while current != None:
            parent = current
            if key < current.key:
                current = current.left
            else:
                current = current.right
        if parent == None:
            self.root = new
        elif key < parent.key:
            parent.left = new
        else:
            parent.right = new

    def find(self, k):
        x = self.root
        while x != None and k != x.key:
            if k < x.key:
                x = x.left
            else:
                x = x.right
        if x != None:
            print('yes')
        else:
            print('no')
        
    def print(self):
        self.print_in_order(self.root)
        print()
        self.print_pre_order(self.root)
        print()

    def print_in_order(self, node):
        if node != None:
            self.print_in_order(node.left)
            print(' ' + str(node.key), end = '')
            self.print_in_order(node.right)
    
    def print_pre_order(self, node):
        if node != None:
            print(' ' + str(node.key), end = '')
            self.print_pre_order(node.left)
            self.print_pre_order(node.right)
        
n = int(input())
bst = BST()
for i in range(n):
    cmd = list(map(str, input().split()))
    if cmd[0] == 'print':
        bst.print()
    elif cmd[0] == 'find':
        bst.find(int(cmd[1]))
    else:
        key = int(cmd[1])
        if cmd[0] == 'insert':
            bst.insert(int(cmd[1]))

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    NIL = -1

    m = int(input())

    root = NIL

    def insert(k):
        global root
        y = NIL
        x = root
        z = {'key':k, 'left':NIL, 'right':NIL}
        while x != NIL:
            y = x
            if z['key'] < x['key']:
                x = x['left']
            else:
                x = x['right']
        z['parent'] = y

        if y == NIL:
            root = z
        elif z['key'] < y['key']:
            y['left'] = z
        else:
            y['right'] = z

    def find(u, k):
        while u != NIL and k != u['key']:
            if k < u['key']:
                u = u['left']
            else:
                u = u['right']
        return u

    def inorder(u):
        if u == NIL:
            return
        inorder(u['left'])
        print(' ' + str(u['key']), end='')
        inorder(u['right'])

    def preorder(u):
        if u == NIL:
            return
        print(' ' + str(u['key']), end='')
        preorder(u['left'])
        preorder(u['right'])

    for _ in range(m):
        command = input()
        if command[0] == 'f':
            _, x = command.split()
            x = int(x)
            t = find(root, x)
            if t != NIL:
                print('yes')
            else:
                print('no')
        elif command[:6] == 'insert':
            _, x = command.split()
            x = int(x)
            insert(x)
        else:
            inorder(root)
            print('')
            # pythonのprintは最後に改行記号をつけてくれるので、これで改行できる
            preorder(root)
            print('')

Submission status: Accepted

Solution code:
def preParse(u):
    if u == None:
        return
    print(' {}'.format(u), end='')
    preParse(nodes[u][1])
    preParse(nodes[u][2])

def inParse(u):
    if u == None:
        return
    inParse(nodes[u][1])
    print(' {}'.format(u), end='')
    inParse(nodes[u][2])

def insert(nodes,z,root):
    x = root
    y = None
    while x != None:
        y = x
        if z < x:
            x = nodes[x][1]
        else:
            x = nodes[x][2]
    nodes[z][0] = y

    if y == None:
        root = z
    elif z < y:
        nodes[y][1] = z
    else:
        nodes[y][2] = z
    return root

def find(nodes,z,root):
    x = root
    while x != None and z != x:
        if z < x:
            x = nodes[x][1]
        else:
            x = nodes[x][2]
    return x

nodes = {}

# {key:[parent,left,right]}

N = int(input())

root = None

for i in range(N):
    order = input().split()
    if order[0] == 'print':
        inParse(root)
        print()
        preParse(root)
        print()
        continue

    z = int(order[1])
    if order[0] == 'insert':
        nodes[z] = [None,None,None]
        root = insert(nodes,z,root)
        continue

    if order[0] == 'find':
        k = find(nodes,z,root)
        if k == z:
            print('yes')
        else:
            print('no')

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
print = sys.stdout.write

class Node:
    __slots__ = ["data", "left", "right"]
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

class BinarySearchTree:
    __slots__ = ["root"]
    def __init__(self):
        self.root = None
    
    def insert(self, data):
        parent = self.root
        if parent is None:
            self.root = Node(data)
            return
        while parent:
            parent_old = parent
            parent = parent.left if data < parent.data else parent.right
        if data < parent_old.data:
            parent_old.left = Node(data)
        else:
            parent_old.right = Node(data)
        
    def find(self, data):
        parent = self.root
        if parent is None:
            print("no\n")
            return
        while parent:
            if parent.data == data:
                print("yes\n")
                return
            parent = parent.left if data < parent.data else parent.right
        print("no\n")
        return


def print_preorder(node):
    print(" {}".format(node.data))
    if node.left:
        print_preorder(node.left)
    if node.right:
        print_preorder(node.right)

def print_inorder(node):
    if node.left:
        print_inorder(node.left)
    print(" {}".format(node.data))
    if node.right:
        print_inorder(node.right)

if __name__ == "__main__":
    n = int(input())
    binary_search_tree = BinarySearchTree()
    for _ in range(n):
        operation, *num = input().split()
        if operation[0] == "i":
            binary_search_tree.insert(int(num[0]))
        elif operation[0] == "f":
            binary_search_tree.find(int(num[0]))
        elif binary_search_tree.root is not None:
            print_inorder(binary_search_tree.root)
            print("\n")
            print_preorder(binary_search_tree.root)
            print("\n")

Submission status: Accepted

Solution code:
class BinarySearchTree:
    def __init__(self):
        self.root = None
        self.order_list = []
    def insert(self, z):
        y = None
        x = self.root
        while x != None:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
    def find(self, key):
        x = self.root
        while x != None:
            if key == x.key:
                return True
            elif key < x.key:
                x = x.left
            else:
                x = x.right
        return False
            
    def walk_preorder(self, node):
        if node == None:
            return None
        self.order_list.append(node.key)
        self.walk_preorder(node.left)
        self.walk_preorder(node.right)
    def walk_inorder(self, node):
        if node == None:
            return None
        self.walk_inorder(node.left)
        self.order_list.append(node.key)
        self.walk_inorder(node.right)
    def print_nodes(self):
        self.order_list = []
        self.walk_inorder(self.root)
        inorder_str = ' '.join(map(str, self.order_list))
        print(' {}'.format(inorder_str))
        self.order_list = []
        self.walk_preorder(self.root)
        preorder_str = ' '.join(map(str, self.order_list))
        print(' {}'.format(preorder_str))
        
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.left = None
        self.right = None

n = int(input())
tree = BinarySearchTree()
for _ in range(n):
    command = input().split(' ')
    if len(command) == 1:
        tree.print_nodes()
    else:
        opecode, operand = command[0], int(command[1])
        if opecode == 'insert':
            node = Node(operand)
            tree.insert(node)
        elif opecode == 'find':
            exists_key = tree.find(operand)
            if exists_key:
                print('yes')
            else:
                print('no')

Submission status: Accepted

Solution code:
class Tree:
    root = None

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

        if not y:
            self.root = node
        elif node.key < y.key:
            y.left = node
        else:
            y.right = node

    def print(self):
        print(' ', end='')
        print(*self.root.print_in())
        print(' ', end='')
        print(*self.root.print_pre())

    def find(self, node):
        y = None
        x = self.root
        while x:
            y = x
            if node.key == x.key:
              break
            elif node.key < x.key:
              x = x.left
            else:
              x = x.right
            
        
        if not y:
            print("no")
        elif node.key == y.key:
            print("yes")
        else:
            print("no")


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

    def print_pre(self):
        yield self.key
        if self.left:
            for k in self.left.print_pre(): yield k
        if self.right:
            for k in self.right.print_pre(): yield k

    def print_in(self):
        if self.left:
            for k in self.left.print_in(): yield k
        yield self.key
        if self.right:
            for k in self.right.print_in(): yield k


tree = Tree()
m = int(input())

while m:
    l = input().split()
    if len(l) == 2 and l[0] == "insert":
       tree.insert(Node(int(l[1])))
    elif len(l) == 2 and l[0] == "find":
       tree.find(Node(int(l[1])))
    else:
       tree.print()
    m -= 1

Submission status: Accepted

Solution code:
"""
二分探索木を構成する
"""
import copy

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

class Tree:
    def insert_root_node(self, new_id):
        global root_node #途中でインスタンス化すると水の泡なんですよ
        root_node = Node(new_id)

    def insert_node(self, root_id, new_id): #new_idは追加するノード
        compare_node = root_node #はじめはrootから比較スタート
        new_node = Node(new_id) #インスタンス化
        while compare_node is not None: #compare_nodeが存在するとき
            #この下の一行は最重要アイディア
            #親の可能性がある時，とりあえず代入して情報を記録しておく
            new_node.parent = compare_node 
            #右か左か
            if compare_node.node_id < new_id:
                compare_node = compare_node.right
            else:
                compare_node = compare_node.left

        #compare_node == Noneの時，上の２つの分岐のどっちからきたかわからない
        #そのため，親と比較し直す必要がある
        if new_node.parent.node_id < new_id:
            new_node.parent.right = Node(new_id)
        else:
            new_node.parent.left = Node(new_id)

def inParse(tmp_node):
    if not tmp_node:
        return
    inParse(tmp_node.left)
    print(' '+str(tmp_node.node_id), end='')
    inParse(tmp_node.right)
        
def preParse(tmp_node):
    if not tmp_node:
        return
    print(' '+str(tmp_node.node_id), end='')
    preParse(tmp_node.left)
    preParse(tmp_node.right)

def find(search_id):
    tmp_node = root_node
    while tmp_node:
        if tmp_node.node_id == search_id:
            print('yes')
            return
        elif tmp_node.node_id < search_id:
            tmp_node = tmp_node.right
        else:
            tmp_node = tmp_node.left
    print('no')



tree = Tree()

n = int(input())
root_id = 0
root_node = None
for i in range(n):
    order = input().split()
    if not root_node: #何も入ってない時
        root_id = int(order[1])
        tree.insert_root_node(int(order[1]))
    elif order[0][0] == 'i':
        new_id = int(order[1])
        tree.insert_node(root_id, new_id)
    elif order[0][0] == 'p':
        node = copy.copy(root_node)
        inParse(node)
        print()
        node = copy.copy(root_node)
        preParse(node)
        print()
    elif order[0][0] == 'f':
        find(int(order[1]))

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = self.left = self.right = None
    
class Tree():
    def __init__(self, root=None):
        self.root = root
    
    def insert(self, node):
        y = None
        x = self.root
        while x is not None:
            y = x
            if node.key < x.key:
                x = x.left
            else:
                x = x.right
        
        node.parent = y
        if y is None:   # Tree が空だった場合
            self.root = node
        elif node.key < y.key:
            y.left = node
        else:
            y.right = node
    
    def print_inorder_tree_walk(self):
        def work(node):
            if node is None:
                return
            work(node.left)
            print('', node.key, end='')
            work(node.right)

        work(self.root)
        print()
    
    def print_preorder_tree_walk(self):
        def work(node):
            if node is None:
                return
            print('', node.key, end='')
            work(node.left)
            work(node.right)

        work(self.root)
        print()

    def find(self, key):
        x = self.root
        while x is not None:
            if key == x.key:
                return True
            elif key < x.key:
                x = x.left
            else:
                x = x.right
        return False

import sys

n = int(input())
T = Tree()
for _ in range(n):
    command, *args = sys.stdin.readline().split()
    if command[0] == 'i':   # insert key
        T.insert(Node(int(args[0])))
    elif command[0] == 'f': # find
        if T.find(int(args[0])):
            print('yes')
        else:
            print('no')
    else:   # print
        T.print_inorder_tree_walk()
        T.print_preorder_tree_walk()

Submission status: Accepted

Solution code:
class Node():
    def __init__(self, parent=-1, left=-1, right=-1):
        self.parent = parent
        self.left = left
        self.right = right


class Tree(dict):
    def __init__(self, obj={}):
        if isinstance(obj, dict):
            super().__init__(obj)
        else:
            raise TypeError
        self.root = -1

    def insert_key(self, key):
        node = Node()
        parent = -1  # targetの親
        target = self.root  # 探索中のkey
        while target != -1:
            parent = target
            if key < target:
                target = self[target].left
            else:
                target = self[target].right
        node.parent = parent
        self[key] = node
        if parent == -1:  # Tが空の場合、最上位の場合
            self.root = key
        elif key < parent:
            self[parent].left = key
        else:
            self[parent].right = key

    def find(self, key):
        try:
            self[key]
            print("yes")
        except KeyError:
            print("no")

    def __preorder(self, id):
        if id == -1:
            return []
        return [id] + self.__preorder(self[id].left) + self.__preorder(self[id].right)

    def __inorder(self, id):
        if id == -1:
            return []
        return self.__inorder(self[id].left) + [id] + self.__inorder(self[id].right)

    def __postorder(self, id):
        if id == -1:
            return []
        return self.__postorder(self[id].left) + self.__postorder(self[id].right) + [id]

    def __preorder_print(self, id):
        if id == -1:
            pass
        else:
            print(" {}".format(id), end="")
            self.__preorder_print(self[id].left)
            self.__preorder_print(self[id].right)

    def __inorder_print(self, id):
        if id == -1:
            pass
        else:
            self.__inorder_print(self[id].left)
            print(" {}".format(id), end="")
            self.__inorder_print(self[id].right)

    def __postorder_print(self, id):
        if id == -1:
            pass
        else:
            self.__postorder_print(self[id].left)
            self.__postorder_print(self[id].right)
            print(" {}".format(id), end="")

    def order_list(self, order_type):
        if order_type == 0:
            return self.__preorder(self.root)
        elif order_type == 1:
            return self.__inorder(self.root)
        else:
            return self.__postorder(self.root)

    def print(self):
        # self.__inorder_print(self.root)
        # print("\n", end="")
        # self.__preorder_print(self.root)
        # print("\n", end="")
        print(" {}".format(" ".join(map(str, self.order_list(1)))))
        print(" {}".format(" ".join(map(str, self.order_list(0)))))


def main():
    n = int(input())
    tree = Tree()
    for _ in range(n):
        operation = input()
        if operation[0] == "i":
            tree.insert_key(int(operation.split()[1]))
        elif operation[0] == "f":
            tree.find(int(operation.split()[1]))
        else:
            tree.print()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def insert(tree,node):
    parent=None
    child=root
    while child is not None:
        parent=child
        if node<child:child=tree[parent][0]
        else:child=tree[parent][1]
    if node<parent:tree[parent][0]=node
    else:tree[parent][1]=node


def In_order(node):
    if node is None:return
    In_order(tree[node][0])
    print(" {}".format(node), end="")
    In_order(tree[node][1])


def Pre_order(node):
    if node is None:return
    print(" {}".format(node), end="")
    Pre_order(tree[node][0])
    Pre_order(tree[node][1])


def find(x,key):
    while x is not None and key!=x:
        if key<x:x=tree[x][0]
        else:x=tree[x][1]
    return x


n=int(input())
tree,root={},None
for i in range(n):
    order=input().split()
    if order[0]=="print":
        In_order(root);print()
        Pre_order(root);print()
    elif order[0]=="find":
        if find(root,int(order[1])) is not None:print("yes")
        else:print("no")
    elif order[0]=="insert":
        num=int(order[1])
        if root is None:
            root=num
            tree[root]=[None,None]
        else:
            tree[num]=[None,None]
            insert(tree,num)

Submission status: Accepted

Solution code:
#! /usr/bin/env python


class NodeBintree:

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

    def insert_node (self, n):
        if (self.key is None) or (self.key > n.key):
            if self.left is None:
                self.left = n
            else:
                self.left.insert_node(n)
        else:
            if self.right is None:
                self.right = n
            else:
                self.right.insert_node(n)
    def find (self, key):
        if self.key is None:
            return self.left.find(key)
        elif self.key == key:
            return "yes"
        elif self.key > key:
            if self.left is None:
                return "no"
            else:
                return self.left.find(key)
        else:
            if self.right is None:
                return "no"
            else:
                return self.right.find(key)

    def traverse_inorder (self):
        ret = ""

        if self.left is not None:
            ret += self.left.traverse_inorder()

        if self.key is not None:
            ret += " {0}".format(self.key)

        if self.right is not None:
            ret += self.right.traverse_inorder()

        return ret

    def traverse_preorder (self):
        ret = ""

        if self.key is not None:
            ret += " {0}".format(self.key)

        if self.left is not None:
            ret += self.left.traverse_preorder()

        if self.right is not None:
            ret += self.right.traverse_preorder()

        return ret

def proc_inputs ():
    num_inputs = int(input())
    inputs = [proc_command(input().split()) for i in range(num_inputs)]
    return inputs

def proc_command (l):
    if len(l) > 1:
        arg = l[1]
    else:
        arg = None
    return {"command": l[0], "arg": arg}

def execute_command (tree, command):
    if command["command"] == "insert":
        tree.insert_node(NodeBintree(int(command["arg"])))

    elif command["command"] == "find":
        print(tree.find(int(command["arg"])))

    elif command["command"] == "print":
        print(tree.traverse_inorder() )
        print(tree.traverse_preorder() )

    return


def main ():
    inputs = proc_inputs()
    tree = NodeBintree(None)
    for command in inputs:
        execute_command(tree, command)
    exit(0)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:


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

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

def find(x, k):
    while x != None and k != x.key:
        if k < x.key:
            x = x.left
        else:
            x = x.right
    return x

def printInOrder(z):
    if z == None:
        return
    if z.left != None:
        printInOrder(z.left)
    inorder.append(str(z.key))
    #print(z.key, end = " ")
    if z.right != None:
        printInOrder(z.right)
        
def printPreOrder(z):
    if z == None:
        return
    #print(z.key, end = " ")
    preorder.append(str(z.key))
    if z.left != None:
        printPreOrder(z.left)
    if z.right != None:
        printPreOrder(z.right)

root = None


n = int(input())
for i in range(n):
    command = input()
    if command[0] == "i":
        com,num = command.split()
        z = Node(int(num))
        insert(root, z)
        if root == None:
            root = z
    elif command[0] == "f":
        com,num = command.split()
        z = Node(int(num))
        x = find(root, int(z.key))
        if x != None:
            print("yes")
        else:
            print("no")

    else:
        inorder = []
        printInOrder(root)
        print(" ", end = "")
        print(' '.join(inorder))
        preorder = []
        printPreOrder(root)
        print(" ", end = "")
        print(' '.join(preorder))