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.key = key
        self.parent = None
        self.left = None
        self.right = None

class Tree():
    def __init__(self):
        self.root = None
        self.list = []

    def insert(self, node):
        y = None                 # x's parent    
        x = self.root
        while x is not None:
            y = x                # set parent
            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 parse_inorder(self, node):
        if node is None:
            return 
        self.parse_inorder(node.left)
        self.list.append(node.key)
        self.parse_inorder(node.right)

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

N = int(input())
T = Tree()
for i in range(N):
    order, *key = input().split()
    if order == "print":
        T.list = []
        T.parse_inorder(T.root)
        print(" " + " ".join(map(str, T.list)))
        T.list = []
        T.parse_preorder(T.root)
        print(" " + " ".join(map(str, T.list)))
    else:
        node = Node(int(key[0]))
        T.insert(node)

Submission status: Accepted

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


root = None

def insert(k):
    global root
    y = None
    x = root
    z = Node(k)

    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
    else:
        if z.key < y.key:
            y.left = z
        else:
            y.right = z


def inorder(u):
    if u is None:
        return
    inorder(u.left)
    print(' %d' % u.key, end='')
    inorder(u.right)


def preorder(u):
    if u is None:
        return
    print(' %d' % u.key, end='')
    preorder(u.left)
    preorder(u.right)


n = int(input())
for i in range(n):
    cmd = input().split()
    if cmd[0] == 'insert':
        insert(int(cmd[1]))
    elif cmd[0] == 'print':
        inorder(root)
        print()
        preorder(root)
        print()

Submission status: Accepted

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

class BST:
	def __init__(self):
		self.root = None
	
	def insert(self, key):
		new = Node(key)
		parent = None
		current = self.root
		while current != None:
			parent = current
			if key < current.key:
				current = current.left
			else:
				current = current.right
		if parent == None:
			self.root = new
		elif key < parent.key:
			parent.left = new
		else:
			parent.right = new		
	
	def find(self, key):
		return
		
	def delete(self, key):
		return
	
	def print(self):
		self.print_in_order(self.root)
		print()
		self.print_pre_order(self.root)
		print()
		
	def print_in_order(self, node):
		if node != None:
			self.print_in_order(node.left)
			print(' ' + str(node.key), end='')
			self.print_in_order(node.right)
		
	def print_pre_order(self, node):
		if node != None:
			print(' ' + str(node.key), end='')
			self.print_pre_order(node.left)
			self.print_pre_order(node.right)		

n = int(input())
bst = BST()
for i in range(n):
	cmd = list(map(str, input().split()))
	if cmd[0] == 'print':
		bst.print()
	else:
		key = int(cmd[1])
		if cmd[0] == 'insert':
			bst.insert(key)
		elif cmd[0] == 'find':
			bst.find(key)
		else:
			bst.delete(key)

Submission status: Accepted

Solution code:
# Binary search trees - Binary Search Tree I
class Tree:
    def __init__(self):
        self.root = None
        self.size = 0
    
    def printorder(self):
        self._preorder_walk(self.root)
        print()
        self._inorder_walk(self.root)
        print()

    def _inorder_walk(self, nd):
        print(' {0}'.format(nd.key), end='')
        if nd.left: self._inorder_walk(nd.left)
        if nd.right: self._inorder_walk(nd.right)

    def _preorder_walk(self, nd):
        if nd.left: self._preorder_walk(nd.left)
        print(' {0}'.format(nd.key), end='')
        if nd.right: self._preorder_walk(nd.right)

class Node:
    def num_child(self):
        d = 1 if self.left else 0
        d += 1 if self.right else 0
        return d
    def __init__(self, key):
        self.key = key
        self.right,self.left = None,None
        self.parent = None
    def __str__(self):
        return 'node key: ' + str(self.key)

def insert(T, z):
    y = None
    x = T.root
    while not x == None:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if z.parent == None:
        T.root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z
    T.size += 1

m = int(input())
T = Tree()
for _ in range(m):
    ss = input().split()
    op = ss[0]
    if op == 'insert':
        v = int(ss[1])
        insert(T, Node(v))
    if op == 'print':
        T.printorder()

Submission status: Runtime Error

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

def insert(node, x):
    if node is None:
        return Node(x)
    elif x == node.key:
        return node
    elif x < node.key:
        node.left = insert(node.left, x)
    else:
        node.right = insert(node.right, x)
    return node

def preorder(node):
    if node == None:
        return None
    l.append(node.key)
    preorder(node.left)
    preorder(node.right)
    return l

def inorder(node):
    if node == None:
        return None
    inorder(node.left)
    l.append(node.key)
    inorder(node.right)
    return l

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

    def insert(self, x):
        self.root = insert(self.root, x)

    def output(self):
        print(self.root.key)
        print(self.root.left.key)
        print(self.root.right.key)

l = []
tree = BinaryTree()
n = int(input())

for i in range(n):
    order = list(map(str, input().split()))
    if order[0] == "insert":
        tree.insert(int(order[1]))
    if order[0] == "print":
        inorder(tree.root)
        for i in range(len(l)):
            if i != len(l)-1:
                print(" ",end="")
                print(l[i],end="")
            else:
                print(" ",end="")
                print(l[i])
        l.clear()

        preorder(tree.root)
        for i in range(len(l)):
            if i != len(l)-1:
                print(" ",end="")
                print(l[i],end="")
            else:
                print(" ",end="")
                print(l[i])
        l.clear()
    else:
        continue

Submission status: Runtime Error

Solution code:
#include<cstdio>
#include<cstdlib>
#include<string>
#include<iostream>
using namespace std;
 
struct Node {
  int key;
  Node *right, *left, *parent;
};
 
Node *root,*NIL;
 
void insert(int k){
  Node *y = NIL;
  Node *x = root;
  Node *z;
 
  z = (Node *)malloc(sizeof(Node));
  z->key = k;
  z->left = NIL;
  z->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;
  } else {
    if ( z->key < y->key ){
      y->left = z;
    }else{
     y->right = z;
    }
  }
}
 
void inorder(Node *u){
  if ( u == NIL ) return;
  inorder(u->left);
  printf(" %d", u->key);
  inorder(u->right);
}
void preorder(Node *u){
  if ( u == NIL)return;
  printf(" %d", u->key);
  preorder(u->left);
  preorder(u->right);
}
 
int main(){
  int n,i,x;
  string com;
 
  scanf("%d",&n);
 
  for( i = 0; i < n; i++){
    cin >> com;
    if(com == "insert"){
      scanf("%d", &x);
      insert(x);
    } else if( com == "print"){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    }
  }
 
  return 0;
}

Submission status: Runtime Error

Solution code:
#include<cstdio>
#include<cstdlib>
#include<string>
#include<vector>
#include<iostream>
using namespace std;

struct Node {
  int key;
  Node *right, *left, *parent;
};

Node *root,*NIL;
bool exist = false;
vector<bool> v;

void insert(int k){
  Node *y = NIL;
  Node *x = root;
  Node *z;

  z = (Node *)malloc(sizeof(Node));
  z->key = k;
  z->left = NIL;
  z->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;
  } else {
    if ( z->key < y->key ){
      y->left = z;
    }else{
     y->right = z;
    }
  }
}

void find(Node *u,int i){
  if( u == NIL){
    return;
  }
  if( u->key == i){
    exist = true;
    v.push_back(true);
    return;
  }
  if(exist == false){
    find(u->left,i);
    find(u->right,i);
  }
}

void inorder(Node *u){
  if ( u == NIL ) return;
  inorder(u->left);
  printf(" %d", u->key);
  inorder(u->right);
}

void preorder(Node *u){
  if ( u == NIL)return;
  printf(" %d", u->key);
  preorder(u->left);
  preorder(u->right);
}

int main(){
  int n,i,x;
  string com;
  vector<string> input;
  vector<int> insert_data;
  vector<int> find_data;
  scanf("%d",&n);

  for(i = 0; i < n; i++){
    cin >> com;
    if(com == "insert"){
      input.push_back("insert");
      scanf("%d", &x);
      insert_data.push_back(x);
    } else if( com == "print"){
      input.push_back("print");
    }else if( com == "find"){
      input.push_back("find");
      scanf("%d", &x);
      find_data.push_back(x);
    }
  }

  int num = input.size();
  for(i = 0;i < num; i++){
    if(input[i] ==  "insert"){
      insert(insert_data[0]);
      insert_data.erase(insert_data.begin());
    }
    if(input[i] == "print"){
      for(auto i: v){
        if(i == true)printf("yes\n");
        else printf("no\n");
      }
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    }
    if(input[i] == "find"){
      exist = false;
      find(root,find_data[0]);
      find_data.erase(find_data.begin());
      if(exist == false)v.push_back(false);
    }
  }

  return 0;
}

Submission status: Runtime Error

Solution code:
class binaryTree:
    def __init__(self,key,p=None,l=None,r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = r

N = int(input())
treelist = [list(input().split()) for i in range(N)]
root = None

def inorder(root):
    x = root
    if x == None:
        return
    inorder(x.l)
    
    global inlist
    inlist.append(x.key)
    
    inorder(x.r)

def insert(root,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.key:
            x = x.l
        else:
            x = x.r
    z.p = y

    if y == None:
        root = z
    elif z.key < y.key:
        y.l = z
    else:
        y.r = z
    return root
    
def outorder(root):
    x = root
    if x == None:
        return
    global outlist
    outlist.append(x.key)
    
    outorder(x.l)
    outorder(x.r)

for data in treelist:
    if data[0] == "insert":
        z = binaryTree(int(data[1]))
        root = insert(root,z)
        
    if data[0] == "print":
        inlist = []
        outlist = []
        
        inorder(root)
        indata = " " + " ".join([str(num) for num in inlist])
        print(indata)
 
        outorder(root)
        outdata = " " + " ".join([str(num) for num in outist])
        print(outdata)

Submission status: Runtime Error

Solution code:


from io import StringIO
class BinaryTree:

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


    def __init__(self):
        self.root = None
        self.output = StringIO()

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        break

    def ini_print_inorder(self):
        self.output = StringIO()
        self.print_inorder(self.root)
        return self.output.getvalue()

    def ini_print_preorder(self):
        self.output = StringIO()
        self.print_preorder(self.root)
        return self.output.getvalue()

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ", file = self.output)
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ", file = self.output)
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

b = BinaryTree()
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    else:
        print(" ", end = "")
        print((b.ini_print_inorder())[:-1])
        print(b.ini_print_preorder()[:-1])

Submission status: Runtime Error

Solution code:
class BinaryTree:

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


    def __init__(self):
        self.root = None
        self.output = StringIO()

    def insert(self, key):
        if self.root is None:
            self.root = self.Node(key)
        else:
            root = self.root
            temp = None
            while True:
                temp = root
                if key > root.key:
                    root = root.right
                    if root is None:
                        temp.right = self.Node(key)
                        break
                else:
                    root = root.left
                    if root is None:
                        temp.left = self.Node(key)
                        break

    def ini_print_inorder(self):
        self.output = StringIO()
        self.print_inorder(self.root)
        return self.output.getvalue()

    def ini_print_preorder(self):
        self.output = StringIO()
        self.print_preorder(self.root)
        return self.output.getvalue()

    def print_inorder(self, node):
        if node is not None:
            self.print_inorder(node.left)
            print(node.key, end = " ", file = self.output)
            self.print_inorder(node.right)

    def print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ", file = self.output)
            self.print_preorder(node.left)
            self.print_preorder(node.right)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

length = int(input())
b = BinaryTree()
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num = comm.split(" ")
        b.insert(int(num))
    else:
        print(" ", end = "")
        print((b.ini_print_inorder())[:-1])
        print(" ", end = "")
        print(b.ini_print_preorder()[:-1])

Submission status: Runtime Error

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

class BST:
  root = None
  def insert(self, k):
    x = self.root
    y = None
    z = Node(k)
    while x is not None:
      y = x
      if z.key < y.key:
        x = x.left
      elif y.key < z.key:
        x = x.right
    
    if y is None:
      # 初回値
      self.root = z
    else:
      if z.key < y.key:
        y.left = z
      elif y.key < z.key:
        y.right = z
        
  def inorder(self):
    # 中間巡回順で出力
    # 単純にソートでいいのでは
    return sorted(self.preorder())
    
  def preorder(self):
    # 先行巡回順で出力
    res = []
    cur_node = self.root
    right_successor = []
    left_successor = []
    # 現在の木がなにもない場合
    if cur_node is None:
      return res
    # そうでない場合
    while cur_node is not None:
      res.append(cur_node.key)
      # 次に調べるやつを追加する
      if cur_node.left is not None:
        left_successor.append(cur_node.left)
      if cur_node.right is not None:
        right_successor.append(cur_node.right)
      # 次に調べるやつを左、右の順でやっていく
      cur_node = left_successor.pop() if len(left_successor) > 0 else right_successor.pop() if len(right_successor) else None
    return res
n = int(input())
bst = BST()
for _ in range(n):
  query = [int(x) if x.isnumeric() else x for x in input().split()]
  if query[0] == 'insert':
    bst.insert(query[1])
  elif query[0] == 'print':
    ans = bst.inorder()
    print(" " + " ".join(list(map(str, ans))))
    ans = bst.preorder()
    print(" " + " ".join(list(map(str, ans))))

Submission status: Runtime Error

Solution code:
import re

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

class BST:
  root = None
  def insert(self, k):
    x = self.root
    y = None
    z = Node(k)
    while x is not None:
      y = x
      if z.key < y.key:
        x = x.left
      elif y.key < z.key:
        x = x.right
    
    if y is None:
      # 初回値
      self.root = z
    else:
      if z.key < y.key:
        y.left = z
      elif y.key < z.key:
        y.right = z
        
  def inorder(self, r):
    # 中間巡回順で出力
    if r != None:
      self.inorder(r.left)
      print(" {}".format(r.key), end="")
      self.inorder(r.right)
      

  def preorder(self, r):
    # 先行巡回順で出力
    if r != None:
      print(" {}".format(r.key), end="")
      self.preorder(r.left)
      self.preorder(r.right)

    
n = int(input())
bst = BST()
for _ in range(n):
  # query = [int(x) if re.match('[+|-]?\d', x) else x for x in input().split()]
  if query[0] == 'insert':
    bst.insert(int(query[1]))
  elif query[0] == 'print':
    root = bst.root
    bst.inorder(root)
    print()
    bst.preorder(root)
    print()

Submission status: Runtime Error

Solution code:
import copy

def selection_sort(A,n):
    for i in range(n):
        minj = i
        for j in range(i,n):
            if A[j] < A[minj]:
                minj = j
        A[i],A[minj] = A[minj], A[i]
    return A

n = int(input())
r = [0]*n
for i in range(n):
    r[i] = input().split()

for i in range(n):
    if r[i][0] == "insert":
        root= int(r[i][1])
        key = i + 1
        break
    

left = []
right = []
for i in range(key, n):
    if r[i][0] == "insert" and int(r[i][1]) < root:
        left += [int(r[i][1])]
    elif r[i][0] == "insert" and int(r[i][1]) > root:
        right += [int(r[i][1])]
    else:
        pre = [root]+ left + right
        a = copy.deepcopy(pre)
        print(" " + *selection_sort(a,len(a)))
        print(" " + *pre)

Submission status: Runtime Error

Solution code:
import copy

def selection_sort(A,n):
    for i in range(n):
        minj = i
        for j in range(i,n):
            if A[j] < A[minj]:
                minj = j
        A[i],A[minj] = A[minj], A[i]
    return A

n = int(input())
r = [0]*n
for i in range(n):
    r[i] = input().split()

for i in range(n):
    if r[i][0] == "insert":
        root= int(r[i][1])
        key = i + 1
        break
    else:
        print()
        print()

left = []
right = []
for i in range(key, n):
    if r[i][0] == "insert" and int(r[i][1]) < root:
        left += [int(r[i][1])]
    elif r[i][0] == "insert" and int(r[i][1]) > root:
        right += [int(r[i][1])]
    elif r
        pre = [root]+ left + right
        a = copy.deepcopy(pre)
        print(pre)
        print("", *selection_sort(a,len(a)))
        print("", *pre)

Submission status: Runtime Error

Solution code:
class Node():
    def __init__(self,id,value):
        self.id = id
        self.child = [None,None]
        self.parent = -1
        self.value = value

    def addChild(self,child):
        self.child = child

    def setParent(self,parent):
        self.parent = parent

nodes = {}

def movePreorder(nodes,order,startNode):
    order.append(startNode.value)
    if startNode.child == [None,None]:
        return
    else:
        for i in startNode.child:
            movePreorder(nodes,order,i)

def moveInorder(nodes,inorder,startNode):
    if startNode.child == [None,None]:
        inorder.append(startNode.value)
    elif len(startNode.child) == 2:
        moveInorder(nodes,inorder,startNode.child[0])
        inorder.append(startNode.value)
        moveInorder(nodes,inorder,startNode.child[1])
    elif len(startNode.child) == 1:
        moveInorder(nodes,inorder,startNode.child[0])
        inorder.append(startNode.value)

n = int(input())
for i in range(n):
    line = input().split(" ")
    command = line[0]

    if command == "print":
        order = []
        kingNode = nodes[0]

        inorder = []
        moveInorder(nodes,inorder,kingNode)
        ans1 = ' '.join(map(str,inorder))
        print(' ' + ans1)

        movePreorder(nodes,order,kingNode)
        ans2 = ' '.join(map(str,order))
        print(' ' + ans2)

    else:
        value = int(line[1])
        if nodes == {}:
            nodes[0] = Node(0,value)
        else:
            start = nodes[0]
            while 1:
                if value <= start.value:
                    if start.child[0] == None:
                        start.child[0] = Node(2,value)
                        break
                    else:
                        start = start.child[0]
                else:
                    if start.child[1] == None:
                        start.child[1] = Node(2,value)
                        break
                    else:
                        start = start.child[1]

Submission status: Runtime Error

Solution code:
class Node():
    def __init__(self,id,value):
        self.id = id
        self.child = [None,None]
        self.parent = -1
        self.value = value

    def addChild(self,child):
        self.child = child

    def setParent(self,parent):
        self.parent = parent

nodes = {}

def movePreorder(nodes,order,startNode):
    order.append(startNode.value)
    if startNode.child == [None,None]:
        return
    else:
        for i in startNode.child:
            movePreorder(nodes,order,i)

def moveInorder(nodes,inorder,startNode):
    if startNode.child == [None,None]:
        inorder.append(startNode.value)
    elif len(startNode.child) == 2:
        moveInorder(nodes,inorder,startNode.child[0])
        inorder.append(startNode.value)
        moveInorder(nodes,inorder,startNode.child[1])
    elif len(startNode.child) == 1:
        moveInorder(nodes,inorder,startNode.child[0])
        inorder.append(startNode.value)

n = int(input())
for i in range(n):
    line = input().split(" ")
    command = line[0]

    if command == "print":
        order = []
        kingNode = nodes[0]

        inorder = []
        moveInorder(nodes,inorder,kingNode)
        ans1 = ' '.join(map(str,inorder))
        print(' ' + ans1)

        movePreorder(nodes,order,kingNode)
        ans2 = ' '.join(map(str,order))
        print(ans2)

    else:
        value = int(line[1])
        if nodes == {}:
            nodes[0] = Node(0,value)
        else:
            start = nodes[0]
            while 1:
                if value <= start.value:
                    if start.child[0] == None:
                        start.child[0] = Node(2,value)
                        break
                    else:
                        start = start.child[0]
                else:
                    if start.child[1] == None:
                        start.child[1] = Node(2,value)
                        break
                    else:
                        start = start.child[1]

Submission status: Runtime Error

Solution code:
class Node():
    def __init__(self,id,value):
        self.id = id
        self.child = [None,None]
        self.parent = -1
        self.value = value

    def addChild(self,child):
        self.child = child

    def setParent(self,parent):
        self.parent = parent

nodes = {}

def movePreorder(nodes,order,startNode):
    order.append(startNode.value)
    if startNode.child == [None,None]:
        return
    else:
        for i in startNode.child:
            movePreorder(nodes,order,i)

def moveInorder(nodes,inorder,startNode):
    if startNode.child == [None,None]:
        inorder.append(startNode.value)
    elif len(startNode.child) == 2:
        moveInorder(nodes,inorder,startNode.child[0])
        inorder.append(startNode.value)
        moveInorder(nodes,inorder,startNode.child[1])
    elif len(startNode.child) == 1:
        moveInorder(nodes,inorder,startNode.child[0])
        inorder.append(startNode.value)

n = int(input())
for i in range(n):
    line = input().split(" ")
    command = line[0]

    if command == "print":
        order = []
        kingNode = nodes[0]

        inorder = []
        moveInorder(nodes,inorder,kingNode)
        ans1 = ' '.join(map(str,inorder))
        print(ans1)

        movePreorder(nodes,order,kingNode)
        ans2 = ' '.join(map(str,order))
        print(' ' + ans2)

    else:
        value = int(line[1])
        if nodes == {}:
            nodes[0] = Node(0,value)
        else:
            start = nodes[0]
            while 1:
                if value <= start.value:
                    if start.child[0] == None:
                        start.child[0] = Node(2,value)
                        break
                    else:
                        start = start.child[0]
                else:
                    if start.child[1] == None:
                        start.child[1] = Node(2,value)
                        break
                    else:
                        start = start.child[1]

Submission status: Runtime 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)print()