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: WA: Presentation Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Mar  2 17:11:49 2019

@author: Yamazaki Kenichi
"""

m = int(input())
A = [list(input().split()) for i in range(m)]

T = [[-1,-1,-1,-1]]
def insert(T,u,x):
    if T[0][3] == -1:
        T[0][3] = x
        return
    if x < T[u][3]:
        if T[u][1] == -1:
            T[u][1] = len(T)
            T.append([u,-1,-1,x])
        else:
            insert(T,T[u][1],x)
    else:
        if T[u][2] == -1:
            T[u][2] = len(T)
            T.append([u,-1,-1,x])
        else:
            insert(T,T[u][2],x)
def ino(u):
    if T[u][1] != -1:
        ino(T[u][1])
    ino_res.append(str(T[u][3]))
    if T[u][2] != -1:
        ino(T[u][2])
def pre(u):
    pre_res.append(str(T[u][3]))
    if T[u][1] != -1:
        pre(T[u][1])
    if T[u][2] != -1:
        pre(T[u][2])
for c in A:
    if c[0] == 'insert':
        insert(T,0,int(c[1]))
    else:
        ino_res = []
        ino(0)
        pre_res = []
        pre(0)
        print(' '.join(ino_res))
        print(' '.join(pre_res))

Submission status: WA: Presentation Error

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

    x = root
    y = None
    while x:x, y = x.left if key < x.key else x.right , x
    if y == None:root = Node(key)
    elif y.key < key:y.right = Node(key)
    else:y.left = Node(key)
        
        
def pre(node):
    if node == None:return
    print('',node.key, end = '');pre(node.left);pre(node.right)
    
def ino(node):
    if node == None:return
    ino(node.left);print('',node.key,end='');ino(node.right)


n = int(input())
root = None
for j in range(n):
    s, *i = input().split()
    if s[0] == 'i':insert(int(i[0]))
    else:
        ino(root);print();pre(root)

Submission status: WA: Presentation Error

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

    x = root
    y = None
    while x:x, y = x.left if key < x.key else x.right , x
    if y == None:root = Node(key)
    elif y.key < key:y.right = Node(key)
    else:y.left = Node(key)
        
        
def pre(node):
    if node == None:return
    print('',node.key, end = '');pre(node.left);pre(node.right)
    
def ino(node):
    if node == None:return
    ino(node.left);print('',node.key,end='');ino(node.right)


n = int(input())
root = None
for j in range(n):
    s, *i = input().split()
    if s[0] == 'i':insert(int(i[0]))
    else:
        ino(root);print(' ');pre(root)

Submission status: WA: Presentation Error

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

    x = root
    y = None
    while x:x, y = x.left if key < x.key else x.right , x
    if y == None:root = Node(key)
    elif y.key < key:y.right = Node(key)
    else:y.left = Node(key)
        
        
def pre(node):
    if node == None:return
    print('',node.key, end = '');pre(node.left);pre(node.right)
    
def ino(node):
    if node == None:return
    ino(node.left);print('',node.key,end='');ino(node.right)


n = int(input())
root = None
for j in range(n):
    s, *i = input().split()
    if s[0] == 'i':insert(int(i[0]))
    else:
        ino(root);print(' \n');pre(root)

Submission status: WA: Presentation Error

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

    x = root
    y = None
    while x:x, y = x.left if key < x.key else x.right , x
    if y == None:root = Node(key)
    elif y.key < key:y.right = Node(key)
    else:y.left = Node(key)
        
        
def pre(node):
    if node == None:return
    print('',node.key, end = '');pre(node.left);pre(node.right)
    
def ino(node):
    if node == None:return
    ino(node.left);print('',node.key,end='');ino(node.right)


n = int(input())
root = None
for j in range(n):
    s, *i = input().split()
    if s[0] == 'i':insert(int(i[0]))
    else:
        ino(root);print('');pre(root)

Submission status: WA: Presentation Error

Solution code:
class Tree():
    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
        z.parent = y
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
    def print(self):
        for order in ['Inorder', 'Preorder']:
            print(*[node.key for node in self.root.walk(order)])
    
class Node():
    def __init__(self, key):
        self.key = key
        self.parent = self.left = self.right = None
    def walk(self, order):
        orders = {'Preorder':[self, self.left, self.right], 'Inorder':[self.left, self, self.right], 'Postorder':[self.left, self.right, self]}
        
        for node in orders[order]:
            if node == self:
                yield node
            elif node:
                for childnode in node.walk(order):
                    yield childnode

                    
                    
tree = Tree()
func = {'insert':tree.insert, 'print':tree.print}

n = int(input())
for _ in range(n):
    command = input().split()
    func[command[0]](*map(int, command[1:]))

Submission status: WA: Presentation Error

Solution code:
import sys
class Tree():
    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
        z.parent = y
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
    def print(self):
        for order in ['Inorder', 'Preorder']:
            print(' '.join([str(node.key) for node in self.root.walk(order)]))
    
class Node():
    def __init__(self, key):
        self.key = key
        self.parent = self.left = self.right = None
    def walk(self, order):
        orders = {'Preorder':[self, self.left, self.right], 'Inorder':[self.left, self, self.right], 'Postorder':[self.left, self.right, self]}
        
        for node in orders[order]:
            if node == self:
                yield node
            elif node:
                for childnode in node.walk(order):
                    yield childnode

                    
                    
tree = Tree()
n = sys.stdin.readline()
for line in sys.stdin:
    if line[0] == 'i':
        tree.insert(int(line.split()[1]))
    else:
        tree.print()

Submission status: WA: Presentation Error

Solution code:
import sys

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

class BST:
    def __init__(self):
        self.root = None
    
    def insert(self, node):
        def helper(root):
            if root is None:
                root = node
            elif node.val < root.val:
                lr = helper(root.left)
                root.left = lr
            else:
                rr = helper(root.right)
                root.right = rr
            return root
            
        self.root = helper(self.root)
    
    def inorder(self):
        def helper(root):
            return [] if root is None else helper(root.left) + [root.val] + helper(root.right)
        return helper(self.root)

    def preorder(self):
        def helper(root):
            return [] if root is None else [root.val] + helper(root.left) + helper(root.right)
        return helper(self.root)

if __name__ == '__main__':
    q = sys.stdin.readline()
    q = int(q)
    bst = BST()
    for i in range(q):
        tmp = sys.stdin.readline()
        if tmp.startswith('print'):
            print ' '.join(map(lambda x: str(x), bst.inorder()))
            print ' '.join(map(lambda x: str(x), bst.preorder()))
        else:
            _, val = tmp.split()
            node = TreeNode(int(val))
            bst.insert(node)

Submission status: WA: Presentation Error

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

def preorder_tree_walk(root):
    result = []
    result.append(root.id)
    if root.left != None:
        result.extend(preorder_tree_walk(root.left))
    if root.right != None:
        result.extend(preorder_tree_walk(root.right))
    return result

def inorder_tree_walk(root):
    result = []
    if root.left != None:
        result.extend(inorder_tree_walk(root.left))
    result.append(root.id)
    if root.right != None:
        result.extend(inorder_tree_walk(root.right))
    return result

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

    if y == None:
        root = z
    elif z.id < y.id:
        y.left = z
    else:
        y.right = z
    return root

n = int(raw_input())
root = None
for i in xrange(n):
    line = raw_input().split()
    if line[0] == 'insert':
        num = int(line[1])
        root = insert(root, Node(num))
    elif line[0] == 'print':
        inorder = inorder_tree_walk(root)
        preoder = preorder_tree_walk(root)
        print ' '.join(map(str, inorder))
        print ' '.join(map(str, preoder))

Submission status: WA: Presentation Error

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

def insert(T,z):
    x=T
    y=None
    while isinstance(x,node):
        y=x
        if z.key<x.key:
            x=x.left
        else:
            x=x.right
    z.parent=y
    if y is None:
        T=z
    elif z.key<y.key:
        y.left=z
    else:
        y.right=z
    return T
        
def preorder(u):
    if not isinstance(u,node):
        return
    pripre.append(str(u.key))
    preorder(u.left)
    preorder(u.right)

def inorder(u):
    if not isinstance(u,node):
        return
    inorder(u.left)
    priin.append(str(u.key))
    inorder(u.right)

pripre=[]
priin=[]
m=input()
root=None
for i in xrange(m):
    cmd=map(str,raw_input().split())
    if cmd[0]=="print":
        preorder(root)
        inorder(root)
        print(' '.join(priin))
        print(' '.join(pripre))
    else:
        key=int(cmd[1])
        z=node(key)
        root=insert(root,z)

Submission status: WA: Presentation Error

Solution code:
# -*- coding: utf-8 -*-

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

def insert(z):
    global root
    y = None
    x = root
    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:
        root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def pre_order(node, list):
    if node is not None:
        list.append(node.key)
        pre_order(node.left, list)
        pre_order(node.right, list)

def in_order(node, list):
    if node is not None:
        in_order(node.left, list)
        list.append(node.key)
        in_order(node.right, list)

m = int(raw_input())
root = None
for i in range(m):
    line = map(str, raw_input().split())
    if line[0] == "insert":
        z = Node_Class(int(line[1]), None, None, None)
        insert(z)
    else:
        A = []
        B = []
        in_order(root, A)
        pre_order(root, B)
        print " ".join(map(str, A))
        print " ".join(map(str, B))

Submission status: WA: Presentation Error

Solution code:
# -*- coding: utf-8 -*-

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

def insert(z):
    global root
    y = None
    x = root
    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:
        root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def pre_order(node):
    if node is not None:
        print node.key,
        pre_order(node.left)
        pre_order(node.right)

def in_order(node):
    if node is not None:
        in_order(node.left)
        print node.key,
        in_order(node.right)

m = int(raw_input())
root = None
for i in range(m):
    line = map(str, raw_input().split())
    if line[0] == "insert":
        z = Node_Class(int(line[1]), None, None, None)
        insert(z)
    else:
        print "",
        in_order(root)
        print ""
        print "",
        pre_order(root)

Submission status: WA: Presentation Error

Solution code:

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

class Tree():
	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
		z.parent = y
		if y == None:
			self.root = z;
		elif z.key < y.key:
			y.left = z
		else:
			y.right = z
	def pre_order(self, node):
		print(" {}".format(node.key), end = "")
		if node.left:
			self.pre_order(node.left)
		if node.right:
			self.pre_order(node.right)
	def in_order(self, node):
		if node.left:
			self.in_order(node.left)
		print(" {}".format(node.key), end = "")
		if node.right:
			self.in_order(node.right)
	def out(self):
		self.in_order(self.root)
		print("")
		self.pre_order(self.root)

tree = Tree()
n = int(input())
for i in range(n):
	c = input().split()
	if c[0] == "insert":
		tree.insert(int(c[1]))
	else:
		tree.out()

Submission status: WA: Presentation Error

Solution code:
from collections import namedtuple
Node = namedtuple('Node', ['p', 'left', 'right'])

def insert(T, z):
    p = None
    x = T['root']
    while x != None:
        p = x
        if z < x: x = T[x].left
        else    : x = T[x].right

    T[z] = Node(p, None, None)

    if p == None:
        T['root'] = z
    elif z < p: T[p] = Node(T[p].p, z, T[p].right)
    else      : T[p] = Node(T[p].p, T[p].left, z)

 
def getInorderList(T, i):
    l = T[i].left
    r = T[i].right
    if l: yield from getInorderList(T, l)
    yield i
    if r: yield from getInorderList(T, r)


def getPreorderList(T, i):
    l = T[i].left
    r = T[i].right
    yield i
    if l: yield from getPreorderList(T, l)
    if r: yield from getPreorderList(T, r)


if __name__=='__main__':
    m = int(input())

    T = {}
    T['root'] = None
    for _ in range(m):        
        op = input().split()
        if op[0] == 'insert': insert(T, int(op[1]))
        else:
            print(*getInorderList(T, T['root']))
            print(*getPreorderList(T, T['root']))

Submission status: WA: Presentation Error

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.p = None
        
        
def insert(root, add):
    parent = None
    pCandidate = root
    while pCandidate is not None:
        parent = pCandidate
        if add.key < pCandidate.key:
            pCandidate = pCandidate.left
        else:
            pCandidate = pCandidate.right
    add.p = parent
    
    if parent is None:
        root = add
    elif add.key < parent.key:
        parent.left = add
    else:
        parent.right = add
    return root

def inorderTreeWalk(node):
    if node.left is not None:
        inorderTreeWalk(node.left)
    print(node.key, end=" ")
    if node.right is not None:
        inorderTreeWalk(node.right)
        
def preorderTreeWalk(node):
    print(node.key, end=" ")
    if node.left is not None:
        preorderTreeWalk(node.left)
    if node.right is not None:
        preorderTreeWalk(node.right)

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

Submission status: WA: Presentation Error

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.p = None
        
        
def insert(root, add):
    parent = None
    pCandidate = root
    while pCandidate is not None:
        parent = pCandidate
        if add.key < pCandidate.key:
            pCandidate = pCandidate.left
        else:
            pCandidate = pCandidate.right
    add.p = parent
    
    if parent is None:
        root = add
    elif add.key < parent.key:
        parent.left = add
    else:
        parent.right = add
    return root

def inorderTreeWalk(node, result):
    if node.left is not None:
        inorderTreeWalk(node.left, result)
    result.append(str(node.key))
    if node.right is not None:
        inorderTreeWalk(node.right, result)
        
def preorderTreeWalk(node, result):
    result.append(str(node.key))
    if node.left is not None:
        preorderTreeWalk(node.left, result)
    if node.right is not None:
        preorderTreeWalk(node.right, result)

n = int(input())
root = None
for i in range(n):
    line = input().split()
    if line[0] == "insert":
        root = insert(root, Node(int(line[1])))
    else:
        result  = []
        inorderTreeWalk(root, result)
        print(" ".join(result))
        del result[:]
        preorderTreeWalk(root, result)
        print(" ".join(result))

Submission status: WA: Presentation Error

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: WA: Presentation Error

Solution code:
class node(object):

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



def insert(T, z):

    if z < T.key:
        if T.left == None:
            k = node(key=z,parent = T)
            T.left = k
            return
        else:
            insert(T.left, z)
            return
    else:
        if T.right == None:
            k = node(key=z,parent = T)
            T.right = k
            return

        else:
            insert(T.right, z)
            return

def disp_tree(root):
    print(' ',root.key,end='')
    if root.left != None:
        disp_tree(root.left)

    if root.right != None:
        disp_tree(root.right)

    return

def disp_tree2(root):
    if root == None:
        return
    else:
        disp_tree2(root.left)

        print(' ',root.key,end='')

        disp_tree2(root.right)

def disp(root):
    disp_tree2(root)
    print()
    disp_tree(root)
    print()


n = int(input())
f = 0
root = node()

for i in range(n):
    input_data = input().split()
    if len(input_data) >= 2:
        command = input_data[0]
        key = int(input_data[1])
        if f == 0 :
            root = node()
            root.key  = key
            f = 1
        else :
            insert(root,key)
    else :
        disp(root)

Submission status: WA: Presentation Error

Solution code:
class node(object):

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



def insert(T, z):

    if z < T.key:
        if T.left == None:
            k = node(key=z,parent = T)
            T.left = k
            return
        else:
            insert(T.left, z)
            return
    else:
        if T.right == None:
            k = node(key=z,parent = T)
            T.right = k
            return

        else:
            insert(T.right, z)
            return


def disp_tree(root):
    global ans
    ans.append(root.key)
    if root.left != None:
        disp_tree(root.left)

    if root.right != None:
        disp_tree(root.right)

    return

def disp_tree2(root):
    global ans

    if root == None:
        return
    else:
        disp_tree2(root.left)

        ans.append(root.key)

        disp_tree2(root.right)

def disp(root):
    global ans
    ans =[]
    disp_tree2(root)
    print(*ans)
    ans =[]
    disp_tree(root)
    print(*ans)
    ans =[]


n = int(input())
f = 0
root = node()

for i in range(n):
    input_data = input().split()
    if len(input_data) >= 2:
        command = input_data[0]
        key = int(input_data[1])
        if f == 0 :
            root = node()
            root.key  = key
            f = 1
        else :
            insert(root,key)
    else :
        disp(root)

Submission status: WA: Presentation Error

Solution code:
class node(object):

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



def insert(T, z):

    if z < T.key:
        if T.left == None:
            k = node(key=z,parent = T)
            T.left = k
            return
        else:
            insert(T.left, z)
            return
    else:
        if T.right == None:
            k = node(key=z,parent = T)
            T.right = k
            return

        else:
            insert(T.right, z)
            return


def disp_tree(root):
    print(' ',root.key,end='')
    if root.left != None:
        disp_tree(root.left)

    if root.right != None:
        disp_tree(root.right)

    return

def disp_tree2(root):


    if root == None:
        return
    else:
        disp_tree2(root.left)

        print(' ',root.key,end='')

        disp_tree2(root.right)

def disp(root):
    disp_tree2(root)
    print()
    disp_tree(root)
    print()


n = int(input())
f = 0
root = node()

for i in range(n):
    input_data = input().split()
    if len(input_data) >= 2:
        command = input_data[0]
        key = int(input_data[1])
        if f == 0 :
            root = node()
            root.key  = key
            f = 1
        else :
            insert(root,key)
    else :
        disp(root)

Submission status: WA: Presentation Error

Solution code:
class node(object):

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



def insert(T, z):

    if z < T.key:
        if T.left == None:
            k = node(key=z,parent = T)
            T.left = k
            return
        else:
            insert(T.left, z)
            return
    else:
        if T.right == None:
            k = node(key=z,parent = T)
            T.right = k
            return

        else:
            insert(T.right, z)
            return


def disp_tree(root):
    print(' ',root.key,end='')
    if root.left != None:
        disp_tree(root.left)

    if root.right != None:
        disp_tree(root.right)

    return

def disp_tree2(root):


    if root == None:
        return
    else:
        disp_tree2(root.left)

        print(' ',root.key,end='')

        disp_tree2(root.right)

def disp(root):
    disp_tree2(root)
    print('\n')
    disp_tree(root)
    print('\n')


n = int(input())
f = 0
root = node()

for i in range(n):
    input_data = input().split()
    if len(input_data) >= 2:
        command = input_data[0]
        key = int(input_data[1])
        if f == 0 :
            root = node()
            root.key  = key
            f = 1
        else :
            insert(root,key)
    else :
        disp(root)

Submission status: WA: Presentation Error

Solution code:
import sys

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

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

    def insert(self, x):
        if self.root is None:
            self.root = Node(x)
            return self

        node = self.root
        while True:
            if x > node.key:
                if node.right is None:
                    node.right = Node(x)
                    break
                else:
                    node = node.right
            elif x < node.key:
                if node.left is None:
                    node.left = Node(x)
                    break
                else: 
                    node = node.left
            else:
                break

        return self

    def pre_order(self):
        keys = []
        self.do_pre_order(self.root, keys)
        print(' '.join(map(str, keys)))

    def do_pre_order(self, node, keys):
        if node is None:
            return
        keys.append(node.key)
        self.do_pre_order(node.left, keys)
        self.do_pre_order(node.right, keys)

    def in_order(self):
        keys = []
        self.do_in_order(self.root, keys)
        print(' '.join(map(str, keys)))

    def do_in_order(self, node, keys):
        if node is None:
            return
        self.do_in_order(node.left, keys)
        keys.append(node.key)
        self.do_in_order(node.right, keys)

# main
tree = BinaryTree()
lines = sys.stdin.readlines()

for line in lines[1:]:
    if len(line.rstrip()) == 0:
        continue

    command = line.rstrip().split(' ')
    
    if command[0] == 'insert':
        tree.insert(int(command[1]))
    elif command[0] == 'print':
        tree.in_order()
        tree.pre_order()
    else:
        raise 'unknown command: ' + command[0]