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:
class Node:
    def __init__(self):
        self.key, self.left, self.right, self.parent = 0, None, None, None

class BST:
    def __init__(self):
        self.root = None
    
    def insert(self, key):
        x, y = self.root, None
        z = Node()
        z.key = key
        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):
        r = self.root
        while r != None:
            if key == r.key:
                break
            elif key < r.key:
                r = r.left
            else:
                r = r.right
        return r
    
    def preOrder(self, r = -1):
        if r == -1: r = self.root
        if r == None:   return
        print("", r.key, end = '')
        self.preOrder(r.left)
        self.preOrder(r.right)
    
    def inOrder(self, r = -1):
        if r == -1: r = self.root
        if r == None:   return
        self.inOrder(r.left)
        print("", r.key, end = '')
        self.inOrder(r.right)

tree = BST()
for _ in range(int(input())):
    s = input()
    if s[0] == 'i':
        tree.insert(int(s[7:]))
    elif s[0] == 'p':
        tree.inOrder()
        print("")
        tree.preOrder()
        print("")
    else:
        print(['no', 'yes'][tree.find(int(s[5:])) != None])

Submission status: Accepted

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

T = {}
root = None

def insert_node(key):
    global root
    x = root
    y = None
    z = Node(None, None, None)
    while x != None:
        y = x
        if key < x:
            x = T[x].left
        else:
            x = T[x].right
    z.parent = y
    if y == None:
        root = key
    else:
        if key < y:
            T[y].left = key
        else:
            T[y].right = key
    T[key] = z

def find_node(key):
    x = root
    while x != None and key != x:
        if key < x:
            x = T[x].left
        else:
            x = T[x].right
    if x != None:
        print('yes')
    else:
        print('no')

def in_print(key, ls):
    if key == None:
        return
    in_print(T[key].left, ls)
    ls.append(key)
    in_print(T[key].right, ls)

def pre_print(key, ls):
    if key == None:
        return
    ls.append(key)
    pre_print(T[key].left, ls)
    pre_print(T[key].right, ls)

def print_node():
    in_ls, pre_ls = [], []
    in_print(root, in_ls)
    pre_print(root, pre_ls)
    print('', *in_ls)
    print('', *pre_ls)

N = int(input())
for i in range(N):
    com = input().split()
    if com[0] == 'insert':
        insert_node(int(com[1]))
    if com[0] == 'find':
        find_node(int(com[1]))
    elif com[0] == 'print':
        print_node()

Submission status: Accepted

Solution code:
import sys
my_input = sys.stdin.readline


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

    def __init__(self):
        self.root = None

    def insert(self, target_key):
        parent = None
        attention = self.root
        target = self.Node(target_key)

        while attention:
            parent = attention
            if target.key < attention.key:
                attention = attention.left
            else:
                attention = attention.right
        target.parent = parent

        if parent is None:
            self.root = target
        elif target.key < parent.key:
            parent.left = target
        else:
            parent.right = target

    def find(self, target_key):
        attention = self.root
        while attention:
            if attention and (attention.key == target_key):
                return attention

            if target_key < attention.key:
                attention = attention.left
            else:
                attention = attention.right

        return False

    def preorder_walk(self, node):
        if node is None:
            return []
        return [node.key] + self.preorder_walk(node.left) + self.preorder_walk(node.right)

    def inorder_walk(self, node):
        if node is None:
            return []
        return self.inorder_walk(node.left) + [node.key] + self.inorder_walk(node.right)


N = int(my_input())
BST = BinarySearchTree()
for _ in range(N):
    command = my_input().split()
    if command[0] == 'insert':
        BST.insert(int(command[1]))

    elif command[0] == 'find':
        print('yes' if BST.find(int(command[1])) else 'no')

    elif command[0] == 'print':
        print(' ' + ' '.join(map(str, BST.inorder_walk(BST.root))))
        print(' ' + ' '.join(map(str, BST.preorder_walk(BST.root))))

Submission status: Accepted

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

    def insert(self,t,key):
        if t.key == None:
            t.key = key
            return
        y = None 
        x = t
        while x is not None:
            y = x
            if key<x.key:x = x.left
            else        :x = x.right
        if y is None  :t = Node(key)
        elif key<y.key:y.left = Node(key)
        else          :y.right = Node(key)

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

    def inorder(self):
        if self.left!=None:self.left.inorder()
        print (' %d'%self.key,end = '')
        if self.right!=None:self.right.inorder()

    def preorder(self):
        print (' %d'%self.key,end = '')
        if self.left!=None:self.left.preorder()
        if self.right!=None:self.right.preorder()

    def walk(self):
        self.inorder()
        print ()
        self.preorder()
        print ()


def main():
    Tree = Node()
    q = int(input())
    for _ in range(q):
        com = list(input().split())
        if com[0] == 'insert':
            Tree.insert(Tree,int(com[1]))
        elif com[0] == 'find':
            print('yes' if Tree.find(Tree,int(com[1])) else 'no')
        else :
            Tree.walk()

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

class BST():
  def __init__(self):
    self.T = list()
    self.root = None
    self.res = []

  def insert(self,node: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:
      self.root = node
    elif node.key < y.key:
      y.left = node
    else:
      y.right = node

  def preorder(self,node:Node):
    if node is None:
      return
    #self.res.append(node.key)
    print(" " + str(node.key), end="")
    self.preorder(node.left)
    self.preorder(node.right)

  def inorder(self, node:Node):
    if node is None:
      return
    self.inorder(node.left)
    print(" " + str(node.key), end="")
    self.res.append(node.key)
    self.inorder(node.right)

  def find(self, key, node:Node ):
    if node is None:
      return False
    if node.key == key:
      return True
    if key < node.key:
      return self.find(key, node.left)
    else:
      return self.find(key, node.right)





def main():
  n = int(input())
  T = BST()
  for _ in range(n):
    cmd = input().split()
    if cmd[0] == "insert":
      key = int(cmd[1])
      T.insert(Node(key))
    elif cmd[0] == "find":
      key = int(cmd[1])
      print ("yes" if T.find(key, T.root) else "no")
    else:
      T.inorder(T.root)
      print()
      T.preorder(T.root)
      print()

if __name__ == "__main__":
  import sys, io

  main()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self):
        self.key = -1
        self.p = -1
        self.l = -1
        self.r = -1

def insert(k):
    y = -1
    x = root[0]
    z = len(T)
    T.append(Node())
    T[z].key = k
    while x != -1:
        y = x
        if T[z].key < T[x].key: x = T[x].l
        else: x = T[x].r
    T[z].p = y
    if y == -1: root[0] = z
    elif T[z].key < T[y].key: T[y].l = z
    else: T[y].r = z

def find(k):
    x = root[0]
    while x != -1 and T[x].key != k:
        if k < T[x].key: x = T[x].l
        else: x = T[x].r
    return x

def inorder(u):
    if u == -1: return
    inorder(T[u].l)
    print(" {}".format(T[u].key),end="")
    inorder(T[u].r)

def preorder(u):
    if u == -1: return
    print(" {}".format(T[u].key),end="")
    preorder(T[u].l)
    preorder(T[u].r)



m = int(input())
T = []
root = [-1]
lst = [input().split() for _ in range(m)]
for i in range(m):
    comm = lst[i][0]
    if len(lst[i]) == 2: key = int(lst[i][1])
    if comm == "insert":
        insert(key)
    elif comm == "find":
        print("yes" if find(key) != -1 else "no")
    else:
        inorder(root[0])
        print("")
        preorder(root[0])
        print("")

Submission status: Accepted

Solution code:
# Binary search tree I 二分探索木：挿入


class Node():

    def __init__(self, k):
        self.k = k
        self.p = None
        self.l = None
        self.r = None
    
    def __repr__(self):
        return str(self.k)


def insert(z):
    if z == T[0]:
        return
    y = None
    x = T[0]
    while x != None:
        y = x 
        if z.k < y.k:
            x = y.l
        else:
            x = y.r
    z.p = y

    if z.k < y.k:
        y.l = z
    else:
        y.r = z


def find(k):
    x = T[0]
    while True:
        if x == None:
            return False
        elif x.k == k:
            return True
        elif x.k > k:
            x = ｘ.l
        elif x.k < k:
            x = x.r


def preparse(u):
    print(" ", u.k, sep="", end="")
    if u.l != None:
        preparse(u.l)
    if u.r != None:
        preparse(u.r)


def inparse(u):
    if u.l != None:
        inparse(u.l)
    print(" ", u.k, sep="", end="")
    if u.r != None:
        inparse(u.r)


m = int(input())
T = [None for i in range(m)]
for id in range(m):
    cmd = input().split()
    if cmd[0] == "insert":
        T[id] = Node(int(cmd[1]))
        insert(T[id])
    elif cmd[0] == "print":
        inparse(T[0])
        print()
        preparse(T[0])
        print()
    elif cmd[0] == "find":
        if find(int(cmd[1])):
            print("yes")
        else:
            print("no")

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:
        y = x
        x = x.left if key < x.key else x.right
    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:
# Binary Search Tree 2

import sys
sys.setrecursionlimit(10**6)


class Node():
    __slots__ = ['key', 'parent', 'left', 'right']

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

    def __repr__(self):
        k = str(self.key)
        p = str(self.parent.key) if self.parent else 'None'
        l = str(self.left.key) if self.left else 'None'
        r = str(self.right.key) if self.right else 'None'
        s = "<Node %s: parent=%s, left=%s, right=%s>" % (k, p, l, r)
        return s


class BinaryTree():
    def __init__(self, n=0):
        self.T = [Node() for _ in range(n)]
        self.root = None

    def preorder(self):
        self.preorder_key = []
        self.preorder_rec(self.root)
        print('', *(self.preorder_key))

    def preorder_rec(self, node):
        if node == None:
            return
        self.preorder_key.append(node.key)
        self.preorder_rec(node.left)
        self.preorder_rec(node.right)

    def inorder(self):
        self.inorder_key = []
        self.inorder_rec(self.root)
        print('', *(self.inorder_key))

    def inorder_rec(self, node):
        if node == None:
            return
        self.inorder_rec(node.left)
        self.inorder_key.append(node.key)
        self.inorder_rec(node.right)

    def insert(self, key):
        node = Node(key)

        y = None
        x = self.root

        while x != None:
            y = x
            if key < x.key:
                x = x.left
            else:
                x = x.right

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

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

    def has(self, key):
        if self.find(self.root, key):
            return True
        else:
            return False


N = int(input())
S = [input() for _ in range(N)]
tree = BinaryTree()

for s in S:
    if 'print' in s:
        tree.inorder()
        tree.preorder()
    else:
        command, key = s.split()
        key = int(key)

        if 'find' in command:
            print('yes' if tree.has(key) else 'no')

        elif 'insert' in command:
            tree.insert(key)

Submission status: Accepted

Solution code:
import sys


class Node():

	def __init__(self,id,key):
		
		self.id = id
		self.key = key
		self.root = -1
		self.left = -1
		self.right = -1
		self.parent = -1
		self.sibling = -1
		self.degree = 0
		self.depth = 0
		self.height = 0

def print_nodes(Nodes,node_id,type,output):

	#TYPE
	#0 : Preorder
	#1 : Inorder
	#2 : Postorder

	if node_id == -1:
		return

	if type == 0:
		output.append(Nodes[node_id].key)

	print_nodes(Nodes,Nodes[node_id].left,type,output)
	if type == 1:
		output.append(Nodes[node_id].key)
	print_nodes(Nodes,Nodes[node_id].right,type,output)
	if type == 2:
		output.append(Nodes[node_id].key)

def insert(T,z):

	if len(T) == 1:
		return


	y = -1
	x = T[0]

	while True:
		y = x
		if z.key < x.key:
			if x.left == -1:
				break
			else:
				x = T[x.left]
		else:
			if x.right == -1:
				break
			else:
				x = T[x.right]

	z.parent = y.id
	if z.key < y.key:
		y.left = z.id
	else:
		y.right = z.id

def find(Nodes,Node,key):

	if Node.key == key:
		return True


	if Node.key > key:
		if Node.left == -1:
			return False
		else:
			return find(Nodes,Nodes[Node.left],key)
	if Node.key < key:
		if Node.right == -1:
			return False
		else:
			return find(Nodes,Nodes[Node.right],key)

	

def test():

	n = int(sys.stdin.readline())
	T = [Node(0,0)] * n
	root = 0
	id = 0

	for i in range(n):

		inputs = sys.stdin.readline().split()

		if inputs[0] == "insert":
			if id == 0:
				T[id] = Node(id,int(inputs[1]))
				id += 1
				continue

			key = int(inputs[1])
			tmp_node = Node(id,key)
			T[id] = tmp_node
			insert(T,tmp_node)
			id += 1

		if inputs[0] == "find":
			result = find(T,T[0],int(inputs[1]))
			if result == False:
				print("no")
			elif result == True:
				print("yes")

		if inputs[0] == "print":
			output = []
			#In-order
			print_nodes(T,T[0].id,1,output)
			for j in range(len(output)-1):
				print(f" {output[j]}",end = '')
			print(f" {output[j+1]}")

			#Pre-order
			output2 = []
			print_nodes(T,T[0].id,0,output2)
			for j in range(len(output2)-1):
				print(f" {output2[j]}",end = '')
			print(f" {output2[j+1]}")

if __name__ == "__main__":
	test()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
n = int(input())
class Node:
  def __init__(self,v):
    self.p = None
    self.key = v
    self.left = None
    self.right = None

sys.setrecursionlimit(1500)
r = None
def insert(z):
  global r
  y = None
  x = r
  while x != None:
    y = x
    if z.key < x.key:
      x = x.left
    else:
      x = x.right
  z.p = y

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

ret = []
def inorder(r):
  if r == None: return
  inorder(r.left)
  ret.append(r.key)
  inorder(r.right)

def preorder(r):
  if r == None: return
  ret.append(r.key)
  preorder(r.left)
  preorder(r.right)

def search(r,key):
  if r == None: return
  if r.key == key:
    return True
  if r.key < key:
    return search(r.right,key)
  else:
    return search(r.left,key)

for i in range(n):
  s = input()
  if s[0]=="i":
    insert(Node(int(s.split()[1])))
  elif s[0]=="f":
    if search(r,int(s.split()[1])):
      print("yes")
    else:
      print("no")
  else:
    ret = []
    inorder(r)
    print(""," ".join(map(str,ret)))
    ret = []
    preorder(r)
    print(""," ".join(map(str,ret)))

Submission status: Accepted

Solution code:
class node():
    def __init__(self, key, parent, left, right):
        self.key = key
        self.parent = parent
        self.left = left
        self.right = right

root = None

def insert(z):
    global root

    y = 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(key):
    
    x = root
    answer = "no"

    while x != None:

        if key == x.key:
            answer = "yes"
            break

        if key < x.key:
            x = x.left
        else:
            x = x.right
    
    return answer

def Inorder_TreeWalk(node):
    if node is None:
        return

    Inorder_TreeWalk(node.left)
    print(" " + str(node.key), end="")
    Inorder_TreeWalk(node.right)

def Preorder_TreeWalk(node):
    if node is None:
            return
            
    print(" " + str(node.key), end="")
    Preorder_TreeWalk(node.left)
    Preorder_TreeWalk(node.right)

def Main():
    
    n = int(input())
    global root

    for i in range(n):
        inp = input().split()
        ope = inp[0]

        if ope == "insert":
            insert(node(int(inp[1]), None, None, None))
        
        elif ope == "find":
            print(find(int(inp[1])))

        elif ope == "print":
            Inorder_TreeWalk(root)
            print()
            Preorder_TreeWalk(root)
            print()
        else:
            pass
Main()

Submission status: Accepted

Solution code:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


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

    def insert(self, val):
        if not self.root:
            self.root = TreeNode(val)
        else:
            parent = None
            cur = self.root
            while cur:
                parent = cur
                if val < cur.val:
                    cur = cur.left
                elif cur.val < val:
                    cur = cur.right

            if val < parent.val:
                parent.left = TreeNode(val)
            elif parent.val < val:
                parent.right = TreeNode(val)

    def find(self, val):
        if not self.root:
            return False
        else:
            cur = self.root
            while cur:
                if val < cur.val:
                    cur = cur.left
                elif cur.val < val:
                    cur = cur.right
                else:
                    return True
            return False

    def remove(self, val):
        self._remove(self.root, val, None)

    def _remove(self, node, val, parent):
        if not node:
            return
        elif val < node.val:
            self._remove(node.left, val, node)
        elif node.val < val:
            self._remove(node.right, val, node)
        else:
            if node.left and node.right:
                # Find min value from right sub-tree
                cur = node.right
                while cur.left:
                    cur = cur.left
                node.val = cur.val
                self._remove(node.right, cur.val, node)
            elif node.left:
                if parent.left == node:
                    parent.left = node.left
                elif parent.right == node:
                    parent.right = node.left
            elif node.right:
                if parent.left == node:
                    parent.left = node.right
                elif parent.right == node:
                    parent.right = node.right
            else:
                if parent.left == node:
                    parent.left = None
                elif parent.right == node:
                    parent.right = None


def inorder(node):
    if node:
        res = []
        res += inorder(node.left)
        res.append(node.val)
        res += inorder(node.right)
        return res
    else:
        return []


def preorder(node):
    if node:
        res = [node.val]
        res += preorder(node.left)
        res += preorder(node.right)
        return res
    else:
        return []


if __name__ == '__main__':
    n = int(input())
    bst = BinarySearchTree()
    for _ in range(n):
        cmd, *num = input().split()
        if cmd == 'insert':
            bst.insert(int(num[0]))
        elif cmd == 'find':
            if bst.find(int(num[0])):
                print('yes')
            else:
                print('no')
        else:
            for x in inorder(bst.root):
                print(f' {x}', end='')
            print()
            for x in preorder(bst.root):
                print(f' {x}', end='')
            print()

Submission status: Accepted

Solution code:
class TreeNode:
  def __init__(self, val):
    self.val = val
    self.left = None
    self.right = None

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

  def insert(self, val):
    node = TreeNode(val)
    if self.root is None: 
      self.root = node
      return

    cur_parent = None
    cur_root = self.root

    while cur_root is not None:
      cur_parent = cur_root
      if val > cur_root.val:
        cur_root = cur_root.right
      else:
        cur_root = cur_root.left

    if val > cur_parent.val:
      cur_parent.right = node
    else:
      cur_parent.left = node

  def find(self, val):
    cur_node = self.root

    while cur_node is not None:
      if cur_node.val == val:
        print("yes")
        return
      elif cur_node.val > val:
        cur_node = cur_node.left
      else:
        cur_node = cur_node.right

    print("no")
    return

  def print(self):
    self.inorder = []
    self.preorder = []
    self.inorder_dfs(self.root)
    self.preorder_dfs(self.root)

    print(" " + " ".join([ str(i) for i in self.inorder ]))
    print(" " + " ".join([ str(i) for i in self.preorder ]))

  def inorder_dfs(self, root):
    if not root: return

    self.inorder_dfs(root.left)
    self.inorder.append(root.val)
    self.inorder_dfs(root.right)

  def preorder_dfs(self, root):
    if not root: return

    self.preorder.append(root.val)
    self.preorder_dfs(root.left)
    self.preorder_dfs(root.right)


n = int(input())
bst = Bst()
for _ in range(n):
  ins = list(map(str, input().split()))
  order = ins[0]
  if order == "insert":
    val = int(ins[1])
    bst.insert(val)
  elif order == "find":
    val = int(ins[1])
    bst.find(val)
  elif order == "print":
    bst.print()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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

class BinaryTree:
    def __init__(self):
        self.root = None
        
    def insert(self, node, parent=None):
        if self.root is None:
            self.root = node
            return
        
        if parent is None:
            parent = self.root
            
        if node.id < parent.id:
            if parent.left:
                self.insert(node, parent.left)
            else:
                parent.left = node
                node.parent = parent
        else:
            if parent.right:
                self.insert(node, parent.right)
            else:
                parent.right = node
                node.parent = parent
    
    def walk_inorder(self, result, current_node=None):
        if current_node is None:
            current_node = self.root
        
        if current_node.left:
            self.walk_inorder(result, current_node.left)
            
        result.append(current_node.id)
        
        if current_node.right:
            self.walk_inorder(result, current_node.right)
    
    def walk_preorder(self, result, current_node=None):
        if current_node is None:
            current_node = self.root
        
        result.append(current_node.id)
        
        if current_node.left:
            self.walk_preorder(result, current_node.left)
            
        if current_node.right:
            self.walk_preorder(result, current_node.right)

    def find_node(self, id, current_node=None):
        if current_node is None:
            current_node = self.root
            
        if current_node.id == id:
            return True
        if id < current_node.id:
            if current_node.left and self.find_node(id, current_node.left):
                return True
        else:
            if current_node.right and self.find_node(id, current_node.right):
                return True
        return False

def main():
    n = int(input())
    tree = BinaryTree()
    
    for _ in range(n):
        cmd = input()
        if cmd[0] == 'p':
            result = []
            tree.walk_inorder(result)
            print('', *result)
            
            result = []
            tree.walk_preorder(result)
            print('', *result)
        elif cmd[0] == 'i':
            id = int(cmd.split()[1])
            node = Node(id)
            tree.insert(node)
        elif cmd[0] == 'f':
            id = int(cmd.split()[1])
            if tree.find_node(id):
                print('yes')
            else:
                print('no')

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys

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

def insert(key):
    global root
    # The first node
    if root.key is None:
        root.key = key
        return
    # The second note and so forth
    else:
        newNode = Node(key)
        x = root
        while x is not None:
            tmpParent = x # parent 候補として保持
            if newNode.key < x.key:
                x = x.left
            else:
                x = x.right
        newNode.parent = tmpParent
        if newNode.key < tmpParent.key:
            tmpParent.left = newNode
        else:
            tmpParent.right = newNode

def find(key):
    """
    Find a node with the key
    :param key: Key to search
    :return: A node that has the key. Returns None if there is no match,
    """
    global root
    x = root
    while x is not None and x.key != key:
        if key < x.key:
            x = x.left
        else:
            x = x.right
    return x

def inorder(node, result):
    if node is None:
        return
    inorder(node.left, result)
    result.append(node.key)
    inorder(node.right, result)

def preorder(node, result):
    if node is None:
        return
    result.append(node.key)
    preorder(node.left, result)
    preorder(node.right, result)

def printOrderedResult(node, orderFunction):
    """
    :param node: node (root)
    :param orderFunction: inorder or preorder (function)
    :return: nothing
    """
    result = []
    orderFunction(node, result)
    result = [i for i in map(str, result)]
    print(' ', end='')
    print(' '.join(result))


# sys.stdin = open('input.txt')

root = Node()
n = int(input())

for i in range(n):
    command = input()
    try:
        command, key = command.split()
        key = int(key)
        if command == 'insert':
            insert(key)
        elif command == 'find':
            if find(key) is None:
                print('no')
            else:
                print('yes')
    except ValueError: # command == 'print'
        printOrderedResult(root, inorder)
        printOrderedResult(root, preorder)