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: Wrong Answer

Solution code:
class BinaryTree:
    def __init__(self):
        self.root = None
    def b_insert(self,x):
        self.root = insert(self.root,x)
    def b_inorder(self):
        inorder(self.root)
    def b_preorder(self):
        preorder(self.root)
        
class Node:
    def __init__(self,x):
        self.data = x
        self.left = None
        self.right = None
            
def insert(node,x):
    if node is None:
        return Node(x)
    elif x == node.data:
        return node
    elif x < node.data:
        node.left = insert(node.left,x)
    else:
        node.right = insert(node.right,x)
    return node
def inorder(node):
    global count
    if node is None:
        return
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    inorder(node.left)
    inorder(node.right)
def preorder(node):
    global count
    if node is None:
        return
    count += 1
    if count != this_len:
        print(node.data,end = " ")
    else:
        print(node.data)
    preorder(node.left)
    preorder(node.right)

length = int(input())
bfs = BinaryTree()
this_len = 0
for l in range(length):
    temp = input()
    if temp[0] == 'i':
        command,num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
        this_len += 1
    else:
        count = 0
        bfs.b_inorder()
        count = 0
        bfs.b_preorder()

Submission status: Wrong Answer

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

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

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

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

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

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

T = BinarySearchTree()
for i in range(int(input())):
  params = input().split()
  if params[0] == "insert":
    T.insert(Node(params[1]))
  if params[0] == "print":
    print_inorder(T.root)
    print("")
    print_preorder(T.root)
    print("")

Submission status: Wrong Answer

Solution code:
#BinarySearchTree
class TreeNode():
    def __init__(self):
        self.key = None
        self.parent = None
        self.left = None
        self.right = None
    def inoder(self):
        r=[]
        if self.left:
            r += self.left.inoder()
        r += [self.key]
        if self.right:
            r += self.right.inoder()
        return r

    def preoder(self):
        r=[self.key]
        if self.left:
            r += self.left.inoder()
        if self.right:
            r += self.right.inoder()
        return r

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

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

    def show(self):
        x = self.root
        print(" " + " ".join(map(str, self.root.inoder())))
        print(" " + " ".join(map(str, self.root.preoder())))
 
 
n = int(input())
Tree = BinaryTree()
for i in range(n):
    L = input().split()
    if L[0] == "insert":
        Node = TreeNode()
        Node.key = int(L[1])
        Tree.insert(Node)
    else:
        Tree.show()

Submission status: Wrong Answer

Solution code:
import sys

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
    
    def insert(node, x):
        if node == None:
            return Node(x)
#==============================================================================
#         elif x == node.data:
#             return node
#==============================================================================
        elif x < node.data:
            node.left = Node.insert(node.left, x)
        else:
            node.right = Node.insert(node.right, x)
        return node
    
    def find(node, x):
        if node.data == x:
            return True
        elif node.left != None and node.data > x:
            return Node.find(node.left, x)
        elif node.right != None and node.data < x:
            return Node.find(node.right, x)
        else:
            return False
        
    def delete(node, x):
        if node.data == x:
            if (node.left == None) and (node.right == None):
                return None
            elif node.left == None:
                return node.right
            elif node.right == None:
                return node.left
            else:
                #????????????
                node.data = Node.serch_min(node.right)
                node.right = Node.delete_min(node.right)
                return node
        elif node.data > x:
            node.left =  Node.delete(node.left, x)
        else:
            node.right = Node.delete(node.right, x)
        return node
        
    def serch_min(node):
        if node.left != None:
            return Node.serch_min(node.left)
        else:
            return node.data
    
    def delete_min(node):
        if node.left == None:
            return node.right
        else:
            node.left = Node.delete_min(node.left)
            return node    
        
    def inorder_print(node):
#==============================================================================
#         if node.left != None:
#             Node.inorder_print(node.left)
#         print("",node.data,  end="")
#         if node.right != None:
#             Node.inorder_print(node.right)
#==============================================================================
        s = ""
        if node.left != None:
            s += Node.inorder_print(node.left)
        s += " " + str(node.data)
        if node.right != None:
            s += Node.inorder_print(node.right)
        return s
    def preorder_print(node):
#==============================================================================
#         print("",node.data,  end="")
#         if node.left != None:
#             Node.preorder_print(node.left)
#         if node.right != None:
#             Node.preorder_print(node.right)
#==============================================================================
        s = ""
        s += " " + str(node.data)
        if node.left != None:
            s += Node.inorder_print(node.left)    
        if node.right != None:
            s += Node.inorder_print(node.right)
        return s
class BinaryTree:
    def __init__(self):
        self.root = None
    
    def insert(self, x):
        self.root = Node.insert(self.root, x)

    def find(self, x):
        if Node.find(self.root, x):
            print("yes")
        else:
            print("no")
            
    def delete(self, x):
        self.root = Node.delete(self.root, x)
        
    def print_tree(self):
#==============================================================================
#         Node.inorder_print(self.root)
#         print()
#         Node.preorder_print(self.root)
#         print()
#==============================================================================
        s = Node.inorder_print(self.root)
        print(s)
        s = Node.preorder_print(self.root)
        print(s)
def main():
    T = BinaryTree()
    m = int(sys.stdin.readline())
    for i in range(m):
        s = sys.stdin.readline().strip()
        if(s == "print"):
            T.print_tree()
        elif s.split()[0] == "find":
            T.find(int(s.split()[1]))
        elif s.split()[0] == "delete":
            T.delete(int(s.split()[1]))
        else:
            z = int(s.split()[1])
            T.insert(z)
        #print(s)
        #T.print_tree()

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
class Node():
    def __init__(self, id, left=-1, right=-1, parent=-1):
        self.id = id
        self.left = left
        self.right = right
        self.parent = parent  
    def show(self):
        print 'node %d: parent = %d, left = %d, right = %d' % (self.id, self.parent, self.left, self.right)

class Stack():
    def __init__(self):
        self.el = []
    def add(self, el):
        self.el.append(el)
    def pop(self):
        return self.el.pop()

def insert(T, z):
    global rootId
    y = None
    if rootId:
        x = T[rootId]
        while x != None:
            y = x
            if z.id < x.id:
                if x.left == -1:
                    break
                x = T[x.left]
            else:
                if x.right == -1:
                    break
                x = T[x.right]
        z.parent = x.id
    if y == None:
        rootId = z.id
    elif z.id < y.id:
        y.left = z.id
    else:
        y.right = z.id
    T[z.id] = z
    return T

### input ###
T = {}
a = []
n = int(raw_input())
rootId = None
for i in range(n):
    tmp = raw_input().split()
    if tmp[0] == 'insert':
        T[int(tmp[1])] = Node(int(tmp[1]))
        T = insert(T, Node(int(tmp[1])))
    elif tmp[0] == 'print':
        break

### inorder ###
pos = rootId
st = Stack()
ans = []
while True:
    if T[pos].left != -1 and T[pos].left not in ans:
        if T[pos].right != -1:
            st.add(T[pos].right)
        st.add(pos)
        pos = T[pos].left
    elif T[pos].left == -1 and T[pos].right != -1 and T[pos].right not in ans:
        ans.append(pos)
        pos = T[pos].right
    else:
        ans.append(pos)
        if len(ans) == len(T):
            break
        pos = st.pop()    
print '', ' '.join(map(str, ans))

### preorder ###
pos = rootId
st = Stack()
ans = []
while True:
    ans.append(pos)
    if len(ans) == len(T):
        break
    if T[pos].left != -1 and T[pos].right != -1:
        st.add(T[pos].right)
    if T[pos].left != -1:
        pos = T[pos].left
    elif T[pos].left == -1 and T[pos].right != -1:
        pos = T[pos].right
    else:
        pos = st.pop()
print '', ' '.join(map(str, ans))

Submission status: Wrong Answer

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

class Tree():
    def __init__(self):
        self.root = None
    def insert(self, key):
        z = Node(key)
        y = None
        x = self.root
        while x:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        
        if y == None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z
        
    def preorder(self, node):
        print(" {}".format(node.key), end = "")
        if node.left:
            self.preorder(node.left)
        if node.right:
            self.preorder(node.right)
            
    def inorder(self, node):
        if node.left:
            self.preorder(node.left)
        print(" {}".format(node.key), end = "")
        if node.right:
            self.preorder(node.right)
            
    def out(self):
        self.inorder(self.root)
        print('')
        self.preorder(self.root)
        print('')

tree = Tree()
N = int(input())
for _ in range(N):
    order = input().split()
    if order[0] == 'insert':
        tree.insert(int(order[1]))
    else:
        tree.out()

Submission status: Wrong Answer

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

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

class BinarySearchTree(list):
    def __init__(self):
        list.__init__(self)
        self.root = None
        
    def insert(self, z):
        z = Node(z)
        y = None
        x = self.root
        
        while x is not None:
            y = x
            if z.key < x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        
        if y is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def preorder(self):
        def preParse(u):
            if u == None:
                return
            print(" " + str(u.key), end="")
            preParse(u.left)
            preParse(u.right)
        preParse(self.root)
        print("")

    def inorder(self):
        def inParse(u):
            if u == None:
                return
            inParse(u.left)
            print(" " + str(u.key), end="")
            inParse(u.right)
        inParse(self.root)
        print("")

if __name__ == '__main__':

    n = int(input())
    command = [input().split(" ") for _ in range(n)]
    T = BinarySearchTree()

    for c in command:
        if c[0] == "insert":
            T.insert(c[1])
        else:
            T.inorder()
            T.preorder()

Submission status: Wrong Answer

Solution code:

Submission status: Wrong Answer

Solution code:
# Binary Search Tree
class Node:
    def __init__(self, v):
        self.value = v
        self.parent = None
        self.left = None
        self.right = None

# 木の根を引数として受け取り，データを挿入した新しい木の根を返す
def insert(node, x):
    if node is None:
        return Node(x)
    elif x == node.value:
        return node
    elif x < node.value:
        node.left = insert(node.left, x)
    else:
        node.right = insert(node.right, x)
    return node

def preorder_walk(node):
    if node:
        yield node.value
        for x in preorder_walk(node.left):
            yield x
        for x in preorder_walk(node.right):
            yield x

def inorder_walk(node):
    if node:
        for x in inorder_walk(node.left):
            yield x
        yield node.value
        for x in inorder_walk(node.right):
            yield x

root = None
n = int(input())
for i in range(n):
    cmd, *val = input().split()
    if cmd == "insert":
        root = insert(root, val[0])
    elif cmd == "print":
        print(*inorder_walk(root))
        print(*preorder_walk(root))

Submission status: Wrong Answer

Solution code:
# Binary Search Tree
class Node:
    def __init__(self, v):
        self.value = v
        self.parent = None
        self.left = None
        self.right = None

# 木の根を引数として受け取り，データを挿入した新しい木の根を返す
def insert_(node, x):
    if node is None:
        return Node(x)
    elif x == node.value:
        return node
    elif x < node.value:
        node.left = insert(node.left, x)
    else:
        node.right = insert(node.right, x)
    return node

# 再帰を使わないパターン
def insert(node):
    global root
    y = None
    x = root
    while x is not None:
        y = x
        if node.value < x.value:
            x = x.left
        else:
            x = x.right
    node.parent = y
    if y is None:
        root = node
    elif node.value < y.value:
        y.left = node
    else:
        y.right = node

def preorder_walk(node):
    if node:
        yield node.value
        for x in preorder_walk(node.left):
            yield x
        for x in preorder_walk(node.right):
            yield x

def inorder_walk(node):
    if node:
        for x in inorder_walk(node.left):
            yield x
        yield node.value
        for x in inorder_walk(node.right):
            yield x

root = None
n = int(input())
for i in range(n):
    cmd, *val = input().split()
    if cmd == "insert":
        #root = insert(root, int(val[0]))
        insert(Node(val[0]))
    elif cmd == "print":
        print("", *inorder_walk(root))
        print("", *preorder_walk(root))

Submission status: Wrong Answer

Solution code:
from collections import deque
from enum import Enum, auto

class Color(Enum):
    WHITE = auto()
    GRAY = auto()
    BLACK = auto()

class BinaryTreeNode():
    def __init__(self, parent=None, left=None, right=None, val=None):
        self.parent = parent
        self.left = left
        self.right = right
        self.val = val
        self.color = Color.WHITE

class BinarySearchTree():
    def __init__(self, n):
        self.root = None
        self.nodes = deque([])
        self.num_nodes = n

    def set_root(self, val):
        node = BinaryTreeNode(val=val)
        self.root = len(self.nodes)
        self.nodes.append(node)

    def insert(self, val):
        y = None
        x = self.root
        while x != None:
            y = x
            if val < self.nodes[x].val:
                x = self.nodes[x].left
            else:
                x = self.nodes[x].right
        node = BinaryTreeNode(val=val, parent=y)

        if y == None:
            self.set_root(val)
        elif node.val < self.nodes[y].val:
            self.nodes[y].left = len(self.nodes)
            self.nodes.append(node)
        else:
            self.nodes[y].right = len(self.nodes)
            self.nodes.append(node)

    def init_color(self):
        for node in self.nodes:
            node.color = Color.WHITE

    def preorder(self):
        self.init_color()
        def preorder_bfs(s):
            print('', self.nodes[s].val, end='')
            self.nodes[s].color = Color.GRAY
            if  self.nodes[s].left != None and self.nodes[self.nodes[s].left].color == Color.WHITE:
                preorder_bfs(self.nodes[s].left)
            if  self.nodes[s].right != None and self.nodes[self.nodes[s].right].color == Color.WHITE:
                preorder_bfs(self.nodes[s].right)
                self.nodes[s].color = Color.BLACK
        preorder_bfs(self.root)
        print('')

    def inorder(self):
        self.init_color()

        inorder_stack = deque([])
        def inorder_dfs_init(s):
            inorder_stack.append(s)
            inorder_dfs()

        def inorder_dfs():
            u = inorder_stack.pop()
            self.nodes[u].color = Color.GRAY
            if self.nodes[u].left != None and self.nodes[self.nodes[u].left].color == Color.WHITE:
                inorder_stack.append(u)
                inorder_stack.append(self.nodes[u].left)
                inorder_dfs()
            print('', self.nodes[u].val, end='')
            if self.nodes[u].right != None and self.nodes[self.nodes[u].right].color == Color.WHITE:
                inorder_stack.append(self.nodes[u].right)
                inorder_dfs()
            self.nodes[u].color = Color.BLACK

        inorder_dfs_init(self.root)
        print('')

def print_elements(ordered):
    for ele in ordered:
        print(' {}'.format(ele), end='')
    print('')

m = int(input())
bst = BinarySearchTree(m)
for i in range(m):
    op = input()
    if op == 'print':
        bst.inorder()
        # print_elements(bst.preorder())
    else:
        num = int(op[7:])
        bst.insert(num)

Submission status: Wrong Answer

Solution code:
class Tree:
    def __init__(self, orders):
        self.root = None
        for order in orders:
            if len(order) == 1:
                self.inorder_print()
                self.preorder_print()
            else:
                self.insert(int(order[1]))

    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 not y:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def inorder_print(self):
        self.root.inorder_print()
        print()

    def preorder_print(self):
        self.root.preorder_print()
        print()


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

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

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


if __name__ == '__main__':
    import sys
    m = int(input())
    orders = [line.strip().split() for line in sys.stdin]
    # orders = [input().split() for i in range(m)]

Submission status: Wrong Answer

Solution code:
class NullNode():
    def __init__(self):
        self.id = -1

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

    def __str__(self):
        return '{} {} {} {} {}'.format(self.id, self.parent.id, self.left.id, self.right.id, self.sibling.id)

def preorder(node, out_list=[]):
    if node.id != -1:
        out_list.append(str(node.id))
        out_list = preorder(node.left, out_list)
        out_list = preorder(node.right, out_list)
    return out_list

def inorder(node, out_list=[]):
    if node.id != -1:
        out_list = inorder(node.left, out_list)
        out_list.append(str(node.id))
        out_list = inorder(node.right, out_list)
    return out_list

def insert(node, root_node):
    temp_node_parent = root_node.parent
    temp_node = root_node

    while temp_node.id != -1:
        temp_node_parent = temp_node
        if node.id < temp_node.id:
            temp_node = temp_node.left
        else:
            temp_node = temp_node.right

    node.parent = temp_node_parent
    if node.id < temp_node_parent.id:
        temp_node_parent.left = node
    else:
        temp_node_parent.right = node




n = int(input())
node_list = []
for i in range(n):
    input_line = [i for i in input().split()]
    if input_line[0] == 'insert':
        id = int(input_line[1])
        id_node = Node(id)
        node_list.append(id_node)
        if i == 0:
            root_node = id_node
        else:
            insert(id_node, root_node)
    else:
        if i != 0:
            inorder_list = inorder(root_node)
            preorder_list = preorder(root_node)
            print(' ' + ' '.join(inorder_list))
            print(' ' + ' '.join(preorder_list))
        else:
            print()

Submission status: Wrong Answer

Solution code:
#coding:utf-8
N = int(input())
trees = [list(input().split()) for i in range(N)]

class BinaryTree:
    def __init__(self,key,p=None,l=None,r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = 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

preList = []
def preOrder(root):
    x = root
    if x == None:
        return
    global preList
    preList.append(x.key)
    
    preOrder(x.l)
    preOrder(x.r)

inList = []
def inOrder(root):
    x = root
    if x == None:
        return
    inOrder(x.l)

    global inList
    inList.append(x.key)
    
    inOrder(x.r)

root = None
for data in trees:
    if data[0] == "insert":
        z = BinaryTree(data[1])
        root = Insert(root,z)


inOrder(root)
inList = " ".join([str(num) for num in inList])
print(inList)

preOrder(root)
preList = " ".join([str(num) for num in preList])
print(preList)

Submission status: Wrong Answer

Solution code:
import sys

tree={}
np = -1

home=0
tree[home]=[None, None, None]

def search(p, x):
    while p != None:
        tmp = tree[p]
        if tmp[0] == x: return True
        if x < tmp:
            p = tmp[1]
        else:
            p = tmp[2]
    return False

def node(x):
    global np
    np += 1
    tree[np] = [x, None, None]
    return np

def insert(p, x):
    if p == None or np == -1: return node(x)
    tmp = tree[p]
    if x== tmp[0]: return p
    elif x<tmp:
        tree[p][1]=insert(tmp[1],x)
    else:
        tree[p][2]=insert(tmp[2],x)
    return p

def preorder(p):
    if p == None: return []
    p1, p2 = tree[p][1:3]
    return [tree[p][0]] + preorder(p1) + preorder(p2)

def inorder(p):
    if p == None: return []
    p1, p2 = tree[p][1:3]
    return inorder(p1) + [tree[p][0]] +inorder(p2)

n = int(input())
i = 0
while i<n:
    s = raw_input()
    if s[0]=='i':
        insert(0,int(s[7:]))
    elif s[0]=='p':
        print ' ' + ' '.join(map(str, inorder(home)))
        print ' ' + ' '.join(map(str, preorder(home)))
    i += 1

Submission status: Time Limit Exceeded

Solution code:
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