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: 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 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))
    else:
#      T.res = list()
      T.inorder(T.root)
      print()
#      print(" ".join(map(str,T.res)))
#      T.res = list()
      T.preorder(T.root)
      print()
#      print(" ".join(map(str,T.res)))

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 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]
for _ in range(m):
    comm = input().split()
    if comm[0] == "insert":
        insert(int(comm[1]))
    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 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()

Submission status: Accepted

Solution code:
def resolve():
    '''
    code here
    '''
    N = int(input())
    queries = [input().split() for _ in range(N)]

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

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

        def insert(self, val):
            if self.root == None:
                self.root = Node(val)
                # print('insert to root', val)
            else:
                # print('insert', val)
                node = self.root
                is_search = True
                while is_search:
                    # print('try insert to ', node.val)
                    if val <= node.val:
                        if node.left:
                            node = node.left
                        else:
                            node.left = Node(val)
                            is_search = False
                    else:
                        if node.right:
                            node = node.right
                        else:
                            node.right = Node(val)
                            is_search = False


        def show_inorder(self, node):
            if node == None:
                return

            self.show_inorder(node.left)
            print('', node.val, end='')
            self.show_inorder(node.right)


        def show_preorder(self, node):
            if node == None:
                return

            print('', node.val, end='')
            self.show_preorder(node.left)
            self.show_preorder(node.right)

    bt = BinaryTree()

    for query, *val in queries:
        if query == 'insert':
            value = int(val[0])
            bt.insert(value)
        else:
            bt.show_inorder(bt.root)
            print('')
            bt.show_preorder(bt.root)
            print('')



if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
# Binary Search Tree 1

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


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

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

Submission status: Accepted

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

class Tree(object):
    def __init__(self):
        self.root = None

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

# 先行順巡回
def preorder(node):
    if node is None:
        return 
    print(" "+str(node.value),end="")    
    preorder(node.left)
    preorder(node.right)
    
# 中間順巡回 
def inorder(node):
    if node is None:
        return 
    inorder(node.left)
    print(" "+str(node.value),end="")
    inorder(node.right)
    
def print_all_node(root):
    stack = [root]
    while stack:
        node = stack.pop()
        print("p: ",node.parent,"r:",node.right,"l:",node.left)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)

if __name__ == "__main__":
    n = int(input())
    T = Tree()
    queries = [input().split() for _ in range(n)]
    for query in queries:
        if query[0] == "print":
            #print_all_node(T.root)
            inorder(T.root)
            print("")
            preorder(T.root)
            print("")

        else:
            command,value = query
            node_z = node()
            node_z.value = int(value)
            if command == "insert":
                insert(T,node_z)

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 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] == "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)

for i in range(n):
  s = input()
  if s[0]=="i":
    insert(Node(int(s.split()[1])))
  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(r, 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 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(root, node(int(inp[1]), None, None, None))

        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 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):
        op = input().split()
        if len(op) == 2:
            bst.insert(int(op[1]))
        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 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 == "print":
    bst.print()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, id):
        self.id=id
        self.parent=self.left=self.right=None
        
    def insert(self, node):
        if node.id < self.id:
            if self.left is None:
                self.left=node
                node.parent=self
            else:
                self.left.insert(node)
        else:
            if self.right is None:
                self.right=node
                node.parent=self
            else:
                self.right.insert(node)
    
    def walk_inorder(self,result):
        if self.left:
            self.left.walk_inorder(result)
        result.append(self.id)
        if self.right:
            self.right.walk_inorder(result)
    
    def walk_preorder(self,result):
        result.append(self.id)
        if self.left:
            self.left.walk_preorder(result)
        if self.right:
            self.right.walk_preorder(result)
        

root=None
n=int(input())
for _ in range(n):
    cmd=input()
    if cmd[0]=='i':
        id=int(cmd.split()[1])
        node=Node(id)
        if root:
            root.insert(node)
        else:
            root=node
    else:
        if root:
            result=[]
            root.walk_inorder(result)
            print('',*result)
            result=[]
            root.walk_preorder(result)
            print('',*result)

Submission status: Accepted

Solution code:
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
            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 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):
    result = []
    orderFunction(node, result)
    result = [i for i in map(str, result)]
    print(' ', end='')
    print(' '.join(result))
    

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

for i in range(n):
    command = input()
    try:
        command, key = command.split()
        key = int(key)
        insert(key)
    except ValueError:
        printOrderedResult(root, inorder)
        printOrderedResult(root, preorder)

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 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:]))
    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 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]))
    else:
        bt.print_tree()

Submission status: Accepted

Solution code:
#time limit exceed
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 print(self):
        print(""," ".join(map(str,self.root.inorder([]))))
        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
    else:
        btree.print()

Submission status: Accepted

Solution code:
class STNode:
    def __init__(self, k, l, r):
        self.key = k
        self.left = l
        self.right = r

def STinsert(h, z):
    p = None
    while True:
        if h.key == -1:
            break
        p = h
        if z.key < h.key:
            h = h.left
        else:
            h = h.right
    
    if z.key < p.key:
        p.left = z
    else:
        p.right = z
    
def preorder(head, h, A):
    if h.key == -1:
        return 
    A.append(h.key)
    preorder(head, h.left, A)
    preorder(head, h.right, A)
    if head == h:
        print('', *A)

def inorder(head, h, B):
    if h.key == -1:
        return 
    inorder(head, h.left, B)
    B.append(h.key)
    inorder(head, h.right, B)
    if head == h:
        print('', *B)

n = int(input())
NULLnode = STNode(-1, None, None)

first = list(input().split())
head = STNode(int(first[1]), NULLnode, NULLnode)
for i in range(n-1):
    temp = list(input().split())
    if temp[0] == 'insert':
        z = STNode(int(temp[1]), NULLnode, NULLnode)
        STinsert(head, z)
    else:
        A = []
        B = []
        inorder(head, head, B)
        preorder(head, head, A)

Submission status: Accepted

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

    from collections import defaultdict

    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 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[:5] == 'print':
            inorder(root)
            print('')
            preorder(root)
            print('')
        else:

            _, k = command.split()
            k = int(k)
            insert(k)

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])

nodes = {}

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

N = int(input())

root = None

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

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

    z = int(order[1])
    nodes[z] = [None,None,None]
    root = insert(nodes,z,root)