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:
import sys
sys.setrecursionlimit(2**20)#再帰回数上限の向上

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

def pre_parse(T:dict, u: int, pre_lis: list):
    if u == None:
        return
    pre_lis.append(u)
    pre_parse(T, T[u].left, pre_lis)
    pre_parse(T, T[u].right, pre_lis)

def in_parse(T,u,in_lis):
    if u == None:
        return
    in_parse(T, T[u].left, in_lis)
    in_lis.append(u)
    in_parse(T, T[u].right, in_lis)

def insert(T, Root, z):
    #zは接点番号（そして接点番号が内容でもある）
    #この接点番号を二分探索木の条件に従うように挿入する
    #もしＴが空なら
    if Root == z:
        T[z] = Node()
    #もしTにいくつか入っていた場合
    else:
        T[z] = Node()#初期化
        x = Root
        while x is not None:
            #子供がNoneになったらbreakする。next_parentが挿入するものの親
            next_parent = x
            if x > z:
                x = T[x].left
                temp = 1
            else:
                x = T[x].right
                temp = 2

        T[z].parent = next_parent
        if temp == 1:
            T[next_parent].left = z
        else:
            T[next_parent].right = z

def find(T,Root,k):
    #Tからkを見つけ出す。ひたすらkの大きさによって左右のパスをたどっていくだけ。
    x = Root
    while x != None and x != k:
        if k < x:
            x = T[x].left
        else:
            x = T[x].right
    return x

def delete_node(T,z):
    # case1指定したzが子を持たないとき
    parent = T[z].parent
    if (T[z].left is None) and (T[z].right is None):
        #そのノードを消去する
        if T[parent].left == z:
            T[parent].left = None
        elif T[parent].right == z:
            T[parent].right = None
        else:
            raise ValueError("something wrong in case 1")

        del T[z]

    #case2 指定した子が一つの子を持つ場合
    elif T[z].right is None:
        #左の子だけある場合、左の子ノードを親に繋ぐ
        #親の左右どちらかにつけるかはzの繋がり方に依存する。
        z_is_left = True if T[parent].left == z else False
        child = T[z].left
        if z_is_left:
            T[parent].left = child
            T[child].parent = parent
            del T[z]
        else:
            T[parent].right = chile
            T[child].parent = parent
            del T[z]

    elif T[z].left is None:
        z_is_left = True if T[parent].left == z else False
        child = T[z].right
        if z_is_left:
            T[parent].left = child
        else:
            T[parent].right = child
        T[child].parent = parent
        del T[z]

    #case3 zが二つの子を持つ場合
    elif (T[z].left is not None) and (T[z].right is not None):
        left, right = T[z].left, T[z].right
        #指定したノードの右部分木の中の子孫の中で最も小さいノードをもらう
        node_next_more = get_min_in_descendants(T,T[z].right)
        next_more_right = T[node_next_more].right
        next_more_parent = T[node_next_more].parent
        #zがRootなら
        if parent is None:
            if node_next_more == right:
                #node_next_moreがrightの場合
                T[right].parent = None
                T[right].left = left
                Root = right
                del T[z]
                return

            else:
                #node_next_moreがもっと下流に存在する場合
                #zの子と親の接続
                T[node_next_more].left = left
                T[node_next_more].right = right
                T[node_next_more].parent = None
                T[left].parent = node_next_more
                T[right].parent = node_next_more
                if next_more_right is not None:
                    T[next_more_right].parent = next_more_parent
                    T[next_more_parent].left = next_more_right
                Root = node_next_more
                del T[z]
                return

        else:
            #zが非Root
            #zが親から見てどっち側についているか
            z_is_left = True if T[parent].left == z else False
            if node_next_more == right:
                if z_is_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more

                T[node_next_more].parent = parent
                T[node_next_more].left = left
                del T[z]
                return
            else:
                #zの親とnext_moreの接続
                if z_is_left:
                    T[parent].left = node_next_more
                else:
                    T[parent].right = node_next_more

                #next_moreと子供との接続
                T[node_next_more].left = T[z].left
                T[node_next_more].right = T[z].right
                T[node_next_more].parent = parent
                T[left].parent = node_next_more
                T[right].parent = node_next_more

                T[next_more_parent].left = next_more_right
                if T[next_more_right] is not None:
                    T[next_more_right].parent = next_more_parent

                del T[z]
                return

def get_min_in_descendants(T,z):
    x = z
    while T[x].left is not None:
        x = T[x].left

    return x

def print_result(T):
    pre_ls = []
    in_ls = []
    in_parse(T,Root,in_ls)
    pre_parse(T,Root,pre_ls)
    print('', *in_ls)
    print('', *pre_ls)

N = int(input())
T = {}
for i in range(N):
    tmp = input()
    if tmp.startswith('print'):
        print_result(T)
    elif tmp.startswith('insert'):
        z = int(tmp.split()[1])
        if i == 0:
            Root = z
        insert(T,Root,z)
    elif tmp.startswith('find'):
        z = int(tmp.split()[1])
        if find(T,Root,z) is None:
            print('no')
        else:
            print('yes')
    elif tmp.startswith('delete'):
        z = int(tmp.split()[1])
        delete_node(T,z)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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[:6] == 'insert':
        _, x = command.split()
        x = int(x)
        insert(x)
    else:
        inorder(root)
        print('')
        # pythonのprintは最後に改行記号をつけてくれるので、これで改行できる
        preorder(root)
        print('')

Submission status: Accepted

Solution code:
import sys
class Node:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None

rt = None


def inorder(node):
    return inorder(node.left) + f' {node.data}' + inorder(node.right) if node else ''
def preorder(node):
    return f' {node.data}' + preorder(node.left) + preorder(node.right) if node else ''



def insert(data):
    global rt
    x, y = rt, None
    while x: x, y = x.left if data < x.data else x.right, x
    if y is None: rt = Node(data)
    elif data < y.data: y.left = Node(data)
    else: y.right = Node(data)

n = int(input())
for e in sys.stdin:
    if e[0] == 'i': insert(int(e[7:]))
    else: print(inorder(rt)); print(preorder(rt))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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

def insert(z):
    global root
    x=root
    y=None
    while x:
        y=x
        if z<x.key:
            x=x.left
        else:
            x=x.right
    
    if y==None:
        root=Node(z)
    elif z<y.key:
        y.left=Node(z)
    else:
        y.right=Node(z)

def preorder(x):
    print(" "+str(x.key),end="")
    if x.left != None:
        preorder(x.left)
    if x.right != None:
        preorder(x.right)
        
def inorder(x):
    if x.left != None:
        inorder(x.left)
    print(" "+str(x.key),end="")
    if x.right != None:
        inorder(x.right)
    

root=None

n=int(input())
for i in range(n):
    tmp=input().split()
    if tmp[0]=="insert":
        insert(int(tmp[1]))
    else:
        inorder(root)
        print("")
        preorder(root)
        print("")

Submission status: Accepted

Solution code:
class BinaryTree:
    class Node:
        def __init__(self, n):
            self.num = n
            self.parent = -1
            self.right = None
            self.left = None

    
    def __init__(self):
        self.root = None


    def insert(self, n):
        if not self.root:
            node = self.Node(n)
            self.root = node
        else:
            current, parent = self.root, None
            while current:
                parent = current
                if n < current.num:
                    current = current.left
                else:
                    current = current.right
            if n < parent.num:
                parent.left = self.Node(n)
            else:
                parent.right = self.Node(n)
            


#    def load(self, tree_info):
#        for i in range(self.node_num):
#            self.nodes[i].num = tree_info[i][0]
#            self.nodes[i].left = tree_info[i][1]
#            self.nodes[i].right = tree_info[i][2]
#            if self.nodes[i].left != -1:
#                self.nodes[self.nodes[i].left].parent = self.nodes[i].num
#            if self.nodes[i].right != -1:
#                self.nodes[self.nodes[i].right].parent = self.nodes[i].num


    
    def print_preorder(self, node):
        if not node.left and not node.right:
            return [node.num]
        elif not node.left:
            return [node.num] + self.print_preorder(node.right)
        elif not node.right:
            return [node.num] + self.print_preorder(node.left)
        else:
            return [node.num] + self.print_preorder(node.left) + self.print_preorder(node.right)


    def print_inorder(self, node):
        if not node.left and not node.right:
            return [node.num]
        elif not node.left:
            return [node.num] + self.print_inorder(node.right)
        elif not node.right:
            return self.print_inorder(node.left) + [node.num]
        else:
            return self.print_inorder(node.left) + [node.num] + self.print_inorder(node.right)


    def print_postorder(self, node):
        if not node.left and not node.right:
            return [node.num]
        elif not node.left:
            return self.print_inorder(node.right) + [node.num]
        elif not node.right:
            return self.print_inorder(node.left) + [node.num]
        else:
            return self.print_inorder(node.left) + self.print_inorder(node.right) + [node.num]



if __name__ == '__main__':
    n = int(input())
    qs = [ input().rstrip().split() for _ in range(n) ]
    bt = BinaryTree()
    for q in qs:
        if q[0] == 'insert':
            bt.insert(int(q[1]))
        elif q[0] == 'print':
            print(' ' + ' '.join(map(str,bt.print_inorder(bt.root))))
            print(' ' + ' '.join(map(str,bt.print_preorder(bt.root))))

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


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


def insert(root, node):
    if root is None:
        root = node
    else:
        if root.val < node.val:
            if root.right is None:
                root.right = node
            else:
                insert(root.right, node)
        else:
            if root.left is None:
                root.left = node
            else:
                insert(root.left, node)


def preorder(root):
    ret = []
    if root is None: return ret
    ret.append(root.val)
    ret.extend(preorder(root.left))
    ret.extend(preorder(root.right))
    return ret


def inorder(root):
    ret = []
    if root is None: return ret
    ret.extend(inorder(root.left))
    ret.append(root.val)
    ret.extend(inorder(root.right))
    return ret


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    s, key = sl()
    root = BinaryNode(int(key))

    for n in range(N - 1):
        input = sl()
        if input[0] == 'print':
            print("", *inorder(root))
            print("", *preorder(root))
        else:
            insert(root, BinaryNode(int(input[1])))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

###
# 二分探索木I
###

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

class BinarySearchTree:
    def __init__(self):
        self.root = None
        self.count = 0
    
    def insert(self, node: Node):
        self.count += 1
        if not self.root:
            self.root = node
            return

        cur = self.root
        while cur:
            if node.val > cur.val:
                if cur.right:
                    cur = cur.right
                    continue
                else:
                    cur.right,node.parent = node,cur
                    return
            else:
                if cur.left:
                    cur = cur.left
                    continue
                else:
                    cur.left,node.parent = node,cur
                    return


def main():

    ## preorder tree walk
    preorder = []

    def preorder_walk(node):
        preorder.append(str(node.val))
        if node.left:
            preorder_walk(node.left)
        if node.right:
            preorder_walk(node.right)

    ## inorder tree walk

    inorder = []

    def inorder_walk(node):
        if node.left:
            inorder_walk(node.left)
        inorder.append(str(node.val))
        if node.right:
            inorder_walk(node.right)


    n = int(input())
    
    bst = BinarySearchTree()
    
    for _ in range(n):
        op = input().strip().split()
        if op[0] == "insert":
            bst.insert(Node(int(op[1])))
        elif op[0] == "print":
            preorder,inorder = [],[]
            preorder_walk(bst.root)
            inorder_walk(bst.root)
            print(""," ".join(inorder))
            print(""," ".join(preorder))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


class Node:
    left = None
    right = None
    key = None

    def __init__(self, key):
        self.key = key
        return


class Tree:

    def __init__(self):
        self.root = None


def insert(T, z):
    '''
    T : Tree
    z : 要素
    '''

    p = None  # x の親（を入れる変数）
    x = T.root

    while x:  # 子がいなかったら
        p = x  # 親を設定
        if z.key < x.key:
            x = x.left  # 左の子へ移動
        else:
            x = x.right  # 右の子へ移動

    if p is None:  # T が空の場合
        T.root = z
    elif z.key < p.key:
        p.left = z  # z を y の左の子にする
    else:
        p.right = z  # z を y の右の子にする


def inorder(v):

    if v.left is not None:
        inorder(v.left)

    print("", v.key, end="")

    if v.right is not None:
        inorder(v.right)

    return


def preorder(r):

    print("", r.key, end="")

    if r.left is not None:
        preorder(r.left)
    if r.right is not None:
        preorder(r.right)

    return


def display(v):

    inorder(v)
    print("")
    preorder(v)
    print("")
    return


def main():

    T = Tree()

    # print(T)

    N = int(sys.stdin.readline().rstrip())
    for _ in range(N):
        op = sys.stdin.readline().rstrip().split()

        if len(op) == 2:
            v = Node(int(op[1]))
            insert(T, v)

        if len(op) == 1:
            display(T.root)


main()

Submission status: Accepted

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

def insert(T, z):
    global root
    
    y = -1
    try:
        x = root
    except:
        x = -1
        root = z
        T[z].root = True
    
    while x != -1:
        y = x
        if T[z].key < T[x].key:
            x = T[x].left
        else:
            x = T[x].right
    T[z].parent = y
    
    if y == -1:
        pass
    
    elif T[z].key < T[y].key:
        T[y].left = z
        
    else:
        T[y].right = z
    
def preParse(u):
    if u == -1:
        return 0
    print(" " + str(T[u].key), end="")
    preParse(T[u].left)
    preParse(T[u].right)

def inParse(u):
    if u == -1:
        return 0
    inParse(T[u].left)
    print(" " + str(T[u].key), end="")
    inParse(T[u].right)

m = int(input().rstrip())

z = 0
T = []
for _ in range(m):
    T.append(BinaryTree(-1, -1, -1))

for _ in range(m):
    command = input().rstrip()
    if command =="print":
        inParse(root)
        print()
        preParse(root)
        print()
    else:
        T[z].key = int(command.split(" ")[-1])
        insert(T, z)
        z += 1

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)

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

def insert(T:dict,z:int):
    global root
    y = -1
    x = root
    while x != -1:
        y = x
        if z < x:
            x = T[x].left
        else:
            x = T[x].right
    T[z] = Node(y,-1,-1)
    
    if y == -1:
        root= z
    elif z < y:
        T[y].left = z
    else:
        T[y].right = z

def inorder(u:int):
    if u == -1:
        return 
    inorder(T[u].left)
    print(" "+str(u),end="")
    inorder(T[u].right)

def preorder(u:int):
    if u == -1:
        return 
    print(" "+str(u),end="")
    preorder(T[u].left)
    preorder(T[u].right)

n = int(input())
root = -1
T = {}
for _ in range(n):
    scan = input().split()
    if len(scan) == 1:
        inorder(root)
        print()
        preorder(root)
        print()
    else:
        insert(T,int(scan[-1]))

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

class Tree:
    root = None
    preorder_list = []
    inorder_list = []
    def __init__(self):
        pass
    def insert(self, 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 == None:
            self.root = node
        elif node.key < y.key:
            y.left = node
        else:
            y.right = node

    def display(self):
        #print(self.root, self.root.key, self.root.parent, self.root.left, self.root.right)
        self.inorder(self.root)
        self.preorder(self.root)
        print(' '+' '.join(map(str, self.inorder_list)))
        print(' '+' '.join(map(str, self.preorder_list)))
        pass

    def preorder(self, node):
        if node == None:
            return
        self.preorder_list.append(node.key)
        if node.left is not None:
            self.preorder(node.left)
        if node.right is not None:
            self.preorder(node.right)

    def inorder(self, node):
        if node == None:
            return
        if node.left is not None:
            self.inorder(node.left)
        self.inorder_list.append(node.key)
        if node.right is not None:
            self.inorder(node.right)

n = int(input())
command_list = [list(input().split()) for _ in range(n)]

tree = Tree()
for command in command_list:
    if command[0] == 'insert':
        node = Node(int(command[1]))
        tree.insert(node)
        #print(node, node.key, node.parent, node.left, node.right)
    if command[0] == 'print':
        tree.display()
        tree.preorder_list = []
        tree.inorder_list = []

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.left = self.right = None
    def preorder(self):
        L = [self.key]
        if self.left: L += self.left.preorder()
        if self.right: L += self.right.preorder()
        return L
    def inorder(self):
        L = []
        if self.left: L += self.left.inorder()
        L.append(self.key)
        if self.right: L += self.right.inorder()
        return L

def insert(t, z):
    y = None
    x = t
    while x:
        y = x # 親を設定
        x = x.left if z.key < x.key else x.right
    z.parent = y
    if not y: # t が空の場合
        return z
    if z.key < y.key:
        y.left = z # z を y の左の子にする
    else:
        y.right = z # z を y の右の子にする
    return t

t = None
m = int(input())
for _ in range(m):
    cmd = list(input().split())
    if cmd[0] == 'insert':
        t = insert(t, Node(int(cmd[1])))
    if cmd[0] == 'print':
        print('', *t.inorder())
        print('', *t.preorder())

Submission status: Accepted

Solution code:
import sys
# def input():
#     return sys.stdin.readline()[:-1]

# n = int(input())
# A = [input().split() for i in range(n)]

class Node():
    __slots__ = ['key', 'left', 'right']
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


def insert(key):
    global root
    x = root # x is current node
    y = None  #  parent of x 
    while x:
        y = x # set parent
        if key < x.key:
            x = x.left # move to left child
        else:
            x = x.right #move to right child
    
    if root is None:
        root = Node(key)
    elif key < y.key: # set z as left child of y
        y.left = Node(key)
    else: 
        y.right = Node(key) # set z as right child of y
        

def inorder(inorder_list, node):
    if node.left is not None:
        inorder(inorder_list, node.left)
    inorder_list.append(str(node.key))
    if node.right is not None:
        inorder(inorder_list, node.right)
    return inorder_list
        
def preorder(preorder_list, node):
    preorder_list.append(str(node.key))
    if node.left is not None:
        preorder(preorder_list, node.left)
    if node.right is not None:
        preorder(preorder_list, node.right)
    return preorder_list
        
root = None

input()
for o in sys.stdin:
    if o[0]=='i':
        insert(int(o[7:]))
    else:
        x = root
        inorder_list = inorder([], x)
        print(' '+' '.join(inorder_list))
        preorder_list = preorder([], x)
        print(' '+' '.join(preorder_list))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2**20)  


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


def pre_parse(T, u, pre_ls):
    if u == None:
        return
    pre_ls.append(u)
    pre_parse(T, T[u].left, pre_ls) 
    pre_parse(T, T[u].right, pre_ls)


def in_parse(T, u, in_ls):
    if u == None:
        return
    in_parse(T, T[u].left, in_ls)
    in_ls.append(u)
    in_parse(T, T[u].right, in_ls)


def insert(T, ROOT, z):
    if ROOT == z:
        T[z] = Node()
    else:
        T[z] = Node()  
        x = ROOT
        while x is not None:  
            next_parent = x  
            if z < x:  
                x = T[x].left
            else:
                x = T[x].right
        T[z].parent = next_parent
        # 親の右と左どっちにつける？
        if z < next_parent:
            T[next_parent].left = z
        else:
            T[next_parent].right = z


def print_result(T):
    pre_ls, in_ls = [], []
    in_parse(T, ROOT, in_ls)
    pre_parse(T, ROOT, pre_ls)
    print('', *in_ls)
    print('', *pre_ls)


n = int(input())
T = {}
for i in range(n):
    tmp = input()
    if i == 0:
        ROOT = int(tmp[7:])
    if tmp[0] == "p":
        print_result(T)
    else:
        insert(T, ROOT, int(tmp[7:]))

Submission status: Accepted

Solution code:
n=int(input())

tree={}
root=None

def insert(tree,number):
    y=None
    x=root
    while x!=None:
        y=x
        if number<x:
            x=tree[y][0]
        else:
            x=tree[y][1]

    if number<y:
        tree[y][0]=number
    else:
        tree[y][1]=number

def preorder(tree,i):
    if i==None:
        return
    print(" {}".format(str(i)),end="")
    preorder(tree,tree[i][0])
    preorder(tree,tree[i][1])

def inorder(tree,i):
    if i==None:
        return
    inorder(tree,tree[i][0])
    print(" {}".format(str(i)),end="")
    inorder(tree,tree[i][1])

for i in range(n):
    tmp=list(input().split())
    if tmp[0]=="insert":
        number=int(tmp[1])
        if root==None:
            root=number
            tree[root]=[None,None]
        else:
            tree[number]=[None,None]
            insert(tree,number)
    
    else:
        inorder(tree,root)
        print()
        preorder(tree,root)
        print()

Submission status: Accepted

Solution code:
import sys, collections
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

class Node():
    key = None
    p = None
    left = None
    right = None

    def __init__(self, key):
        self.key = key

class BinarySearchTree():
    root = None

    def insert(self, 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.p = y

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

    def print_nodes(self):
        inorder = []
        preorder = []

        def dfs(v):
            v_key = v.key
            preorder.append(v_key)
            if v.left is not None:
                dfs(v.left)
            inorder.append(v_key)
            if v.right is not None:
                dfs(v.right)

        dfs(self.root)

        print('', *inorder)
        print('', *preorder)

def resolve():
    n = I()
    T = BinarySearchTree()
    for _ in range(n):
        q = LSS()
        if q[0]=='insert':
            z = Node(int(q[1]))
            T.insert(z)
        else:
            T.print_nodes()

if __name__ == '__main__':
    resolve()