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: Time Limit Exceeded

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):
    # 中間巡回順で出力
    # 単純にソートでいいのでは
    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 re.match('[+|-]?\d', x) 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: Time Limit Exceeded

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(query[1])
  elif query[0] == 'print':
    root = bst.root
    bst.inorder(root)
    print()
    bst.preorder(root)
    print()

Submission status: Time Limit Exceeded

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()]
  query = 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: Time Limit Exceeded

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: Time Limit Exceeded

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('', *[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(sys.stdin.readline())
for _ in range(n):
    command = sys.stdin.readline().split()
    func[command[0]](*map(int, command[1:]))

Submission status: Time Limit Exceeded

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: Time Limit Exceeded

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: Time Limit Exceeded

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_A
# Binary Search Tree I
# Result:
import sys

class BinarySearchTree(object):
    def __init__(self):
        super(BinarySearchTree, self).__init__()
        self.root = None
        self.count = 0

    def insert(self, val):
        node = Node(val)
        y = None
        x = self.root
        while x != None:
            y = x
            if node.id_ < x.id_:
                x = x.left
            else:
                x = x.right
        node.parent = y

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

    def __str__(self):
        return 'Call to_inorder_walk() or to_preorder_walk()'

    def to_inorder_walk(self):
        return self._to_inorder_walk(self.root)

    def to_preorder_walk(self):
        return self._to_preorder_walk(self.root)

    def _to_inorder_walk(self, node):
        if node == None: return ''
        str_ = self._to_inorder_walk(node.left)
        str_ += ' %d' % (node.id_)
        str_ += self._to_inorder_walk(node.right)
        return str_

    def _to_preorder_walk(self, node):
        if node == None: return ''
        str_ = ' %d' % (node.id_)
        str_ += self._to_preorder_walk(node.left)
        str_ += self._to_preorder_walk(node.right)
        return str_

class Node(object):
    def __init__(self, id_):
        super(Node, self).__init__()
        self.id_ = id_
        self.parent = None
        self.left = None
        self.right = None

    def __str__(self):
        str_ = '%d' % (self.id_)
        return str_


bst = BinarySearchTree()

_nops = int(sys.stdin.readline())
i = 0
for _ in range(0, _nops):
    op = sys.stdin.readline().rstrip().split(' ')
    if op[0] == 'insert':
        bst.insert(int(op[1]))
    elif op[0] == 'print':
        print bst.to_inorder_walk()
        print bst.to_preorder_walk()
    else:
        pass

Submission status: Time Limit Exceeded

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: Time Limit Exceeded

Solution code:
from __future__ import print_function
class Node:
    def __init__(self, id):
        self.id = id
        self.left = None
        self.right = None
        self.parent = None

def preorder_tree_walk(root):
    print('', root.id, end='')
    if root.left != None:
        preorder_tree_walk(root.left)
    if root.right != None:
        preorder_tree_walk(root.right)

def inorder_tree_walk(root):
    if root.left != None:
        inorder_tree_walk(root.left)
    print('', root.id, end='')
    if root.right != None:
        inorder_tree_walk(root.right)

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_tree_walk(root)
        print()
        preorder_tree_walk(root)
        print()

Submission status: Time Limit Exceeded

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

def insert(tree,k):
    y = None
    x = tree
    z = Node(k)
    while x != None:
        y = x
        if x.key > k:
            x = x.left
        else:
            x = x.right
    z.p = y
    if y == None:
        tree = z
    elif y.key > k:
        y.left = z
    else:
        y.right = z
    return tree

def middleorder(x):
    if x != None:
        middleorder(x.left)
        print x.key,
        middleorder(x.right)

def preorder(x):
    if x != None:
        print x.key,
        preorder(x.left)
        preorder(x.right)



tree = None
m = int(raw_input())
for i in range(m):
    c = raw_input().strip()
    if c[0] == 'i':
        tree = insert(tree, int(c[7:]))
    elif c[0] == 'p':
        print '',
        middleorder(tree)
        print
        print '',
        preorder(tree)
        print

Submission status: Time Limit Exceeded

Solution code:

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


def insert(T, z): #(T, Node)
    y = -1
    x = T[0] #Node()
    while x != -1 :
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y == -1:
        T[0] = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z


def preParse(T):
    if T == -1 and T == -1:
        return
    print T.key,
    preParse(T.left)
    preParse(T.right)

def inParse(T):
    if T == -1 and T == -1:
        return
    inParse(T.left) #Node() or -1
    print T.key,
    inParse(T.right)


T = [-1]

def main():
    com = []
    m = int(raw_input())
    for i in xrange(m):
        com.append(raw_input())
    for i in xrange(m):
        if com[i][0] == 'i':
            insert(T,Node(key=int(com[i][7:])))
        else:
            print '',
            inParse(T[0])
            print
            print '',
            preParse(T[0])
            print 
    return 0

main()

Submission status: Time Limit Exceeded

Solution code:

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


def insert(T_, z): #(T, Node)
    global T
    y = -1
    x = T_ #Node()
    while x != -1 :
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y == -1:
        T = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z


def preParse(T):
    if T == -1 and T == -1:
        return
    print T.key,
    preParse(T.left)
    preParse(T.right)

def inParse(T):
    if T == -1 and T == -1:
        return
    inParse(T.left) #Node() or -1
    print T.key,
    inParse(T.right)


T = -1

def main():
    com = []
    m = int(raw_input())
    for i in xrange(m):
        com.append(raw_input())
    for i in xrange(m):
        if com[i][0] == 'i':
            insert(T,Node(key=int(com[i][7:])))
        else:
            print '',
            inParse(T)
            print
            print '',
            preParse(T)
            print 
    return 0

main()

Submission status: Time Limit Exceeded

Solution code:

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


def insert(T_, z): #(T, Node)
    global T
    y = -1
    x = T_ #Node()
    while x != -1 :
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y == -1:
        T = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z


def preParse(T):
    #if T == -1 and T == -1:
    #    return
    print T.key,
    if T.left != -1:
        preParse(T.left)
    if T.right != -1:
        preParse(T.right)

def inParse(T):
    #if T == -1 and T == -1:
    #    return
    if T.left != -1:
        inParse(T.left) #Node() or -1
    print T.key,
    if T.right != -1:    
        inParse(T.right)


T = -1

def main():
    com = []
    m = int(raw_input())
    for i in xrange(m):
        com.append(raw_input())
    for i in xrange(m):
        if com[i][0] == 'i':
            insert(T,Node(key=int(com[i][7:])))
        else:
            print '',
            inParse(T)
            print
            print '',
            preParse(T)
            print 
    return 0

main()

Submission status: Time Limit Exceeded

Solution code:

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


def insert(T_, z): #(T, Node)
    global T
    y = -1
    x = T_ #Node()
    while x != -1 :
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y == -1:
        T = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z


def preParse(T):
    if T == -1 :
        return
    print T.key,
    preParse(T.left)
    preParse(T.right)

def inParse(T):
    if T == -1 :
        return
    inParse(T.left) #Node() or -1
    print T.key,
    inParse(T.right)


T = -1

def main():
    com = []
    m = int(raw_input())
    for i in xrange(m):
        com.append(raw_input())
    for i in xrange(m):
        if com[i][0] == 'i':
            insert(T,Node(key=int(com[i][7:])))
        else:
            print '',
            inParse(T)
            print
            print '',
            preParse(T)
            print 
    return 0

main()

Submission status: Time Limit Exceeded

Solution code:

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


def insert(T_, z): #(T, Node)
    global T
    y = -1
    x = T_ #Node()
    while x != -1 :
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.parent = y
    if y == -1:
        T = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z


def preParse(T):
    if T == -1 :
        return
    print T.key,
    preParse(T.left)
    preParse(T.right)

def inParse(T):
    if T == -1 :
        return
    inParse(T.left) #Node() or -1
    print T.key,
    inParse(T.right)


T = -1

def main():
    com = ''
    m = int(raw_input())
    #for i in xrange(m):
    #    com.append(raw_input())
    for i in xrange(m):
        com = raw_input()
        if com[0] == 'i':
            insert(T,Node(key=int(com[7:])))
        else:
            print '',
            inParse(T)
            print
            print '',
            preParse(T)
            print 
    return 0

main()

Submission status: Time Limit Exceeded

Solution code:
import sys

class binarySearchTree:
    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

        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def printBT(self):
        print self.root.inorderTreeWalk()
        print self.root.preorderTreeWalk()

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

    def inorderTreeWalk(self):
        ret = ""
        if self.left:
            ret += self.left.inorderTreeWalk()
        ret += " " + str(self.key)
        if self.right:
            ret += self.right.inorderTreeWalk()

        return ret

    def preorderTreeWalk(self):
        ret = " " + str(self.key)
        if self.left:
            ret += self.left.preorderTreeWalk()
        if self.right:
            ret += self.right.preorderTreeWalk()

        return ret

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    bt = binarySearchTree()
    for line in lines:
        if line[0] == "i":
            bt.insert(int(line[6:]))
        else:
            bt.printBT()

Submission status: Time Limit Exceeded

Solution code:
import sys

class binarySearchTree:
    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

        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def printBT(self):
        print self.root.inorderTreeWalk()
        print self.root.preorderTreeWalk()

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

    def inorderTreeWalk(self):
        ret = ""
        if self.left:
            ret += self.left.inorderTreeWalk()
        ret += " " + str(self.key)
        if self.right:
            ret += self.right.inorderTreeWalk()

        return ret

    def preorderTreeWalk(self):
        ret = " " + str(self.key)
        if self.left:
            ret += self.left.preorderTreeWalk()
        if self.right:
            ret += self.right.preorderTreeWalk()

        return ret

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    bt = binarySearchTree()
    for line in lines:
        if line[0] == "i":
            t = line.split()
            bt.insert(int(t[1]))
        else:
            bt.printBT()

Submission status: Time Limit Exceeded

Solution code:
import sys

class binarySearchTree:
    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

        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def printBT(self):
        print self.root.inorderTreeWalk()
        print self.root.preorderTreeWalk()

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

    def inorderTreeWalk(self):
        ret = ""
        if self.left:
            ret += self.left.inorderTreeWalk()
        ret += " " + str(self.key)
        if self.right:
            ret += self.right.inorderTreeWalk()

        return ret

    def preorderTreeWalk(self):
        ret = " " + str(self.key)
        if self.left:
            ret += self.left.preorderTreeWalk()
        if self.right:
            ret += self.right.preorderTreeWalk()

        return ret

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    bt = binarySearchTree()
    for line in lines:
        if line[0] == "i":
            bt.insert(int(line.split()[1]))
        else:
            bt.printBT()

Submission status: Time Limit Exceeded

Solution code:
import sys

class binarySearchTree:
    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

        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def printBT(self):
        print inorderTreeWalk(self.root)
        print preorderTreeWalk(self.root)

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

def inorderTreeWalk(node):
    if node:
        return inorderTreeWalk(node.left) + " " + str(node.key) + inorderTreeWalk(node.right)
    return ""

def preorderTreeWalk(node):
    if node:
        return " " + str(node.key) + preorderTreeWalk(node.left) + preorderTreeWalk(node.right)
    return ""

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    del lines[0]

    bt = binarySearchTree()
    for line in lines:
        if line[0] == "i":
            bt.insert(int(line.split()[1]))
        else:
            bt.printBT()