Problem:

  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

 Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. 

  Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

 Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

  The following figure shows an example of the binary search tree.

  For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

  A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

  To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2     y = NIL // parent of x
3     x = 'the root of T'
4     while x &ne; NIL
5         y = x // set the parent
6         if z.key < x.key
7             x = x.left // move to the left child
8         else 
9             x = x.right // move to the right child
10    z.p = y
11
12    if y == NIL // T is empty
13        'the root of T' = z
14    else if z.key < y.key
15        y.left = z // z is the left child of y
16    else 
17        y.right = z // z is the right child of y

  Write a program which performs the following operations to a binary search tree $T$.

insert  $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and  preorder tree walk respectively.

  You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

  In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

  For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print


Sample output:
 1 12 17 20 25 30 88
 30 12 1 20 17 25 88

Submission status: Accepted

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

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

def inoder(x):
    if x == None: return []
    else:
        r = []
        r.extend(inoder(x.left))
        r.append(str(x.key))
        r.extend(inoder(x.right))
    return r

def preoder(x):
    if x == None: return []
    else:
        r = []
        r.append(str(x.key))
        r.extend(preoder(x.left))
        r.extend(preoder(x.right))
    return r

def show(x):
    print(" " + " ".join(inoder(x)))
    print(" " + " ".join(preoder(x)))


root = None
n = int(input())
for i in range(n):
    L = input().split()
    if L[0] == "insert":
        T = BinaryTree()
        T.key = int(L[1])
        insert(T)
    else:
        show(root)

Submission status: Accepted

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.preoder()
        if self.right:
            r += self.right.preoder()
        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: Accepted

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.preorder_print(node.left)    
        if node.right != None:
            s += Node.preorder_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: Accepted

Solution code:
# coding=utf-8

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

    def insert(self, key):
        node = Node(key)
        flag = False

        if self.root == None:
            self.root = node
        else:
            search_node = self.root
            while search_node:
                final_node = search_node
                if final_node.key < key:
                    search_node = final_node.right
                    flag = 'right'
                else:
                    search_node = final_node.left
                    flag = 'left'
            node.parent = final_node
            if flag == 'right':
                final_node.right = node
            elif flag == 'left':
                final_node.left = node

    def print_tree(self):
        prewalked = self.root.prewalk()
        inwalked = self.root.inwalk()
        print(' ', end = '')
        print(*inwalked)
        print(' ', end = '')
        print(*prewalked)


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

    def prewalk(self):
        result = []
        result += [self.key] # ??¢?´¢????????? #
        if self.left:
            result += self.left.prewalk()
        if self.right:
            result += self.right.prewalk()
        #print("self.key:", self.key, result) #debugger
        return result



    def inwalk(self):
        result = []
        if self.left:
            result += self.left.inwalk()
        result += [self.key] # ??¢?´¢????????? #
        if self.right:
            result += self.right.inwalk()
        #print("self.key:", self.key, result) #debugger
        return result


n = int(input())
tree = Tree()
for _ in range(n):
    order, *key = input().split()
    if order == 'insert':
        tree.insert(int(key[0]))
    else:
        tree.print_tree()

Submission status: Accepted

Solution code:
import sys


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

    def preorder(self):
        nodeList = [self.key]
        if self.left:
            nodeList += self.left.preorder()
        if self.right:
            nodeList += self.right.preorder()
        return nodeList

    def inorder(self):
        nodeList = []
        if self.left:
            nodeList += self.left.inorder()
        nodeList += [self.key]
        if self.right:
            nodeList += self.right.inorder()
        return nodeList


class BinaryTree():
    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 is None:
            self.root = z
        elif z.key < y.key:
            y.left = z
        else:
            y.right = z

    def print(self):
        print(" " + " ".join(map(str, self.root.inorder())))
        print(" " + " ".join(map(str, self.root.preorder())))


if __name__ == "__main__":
    tree = BinaryTree()
    n = int(sys.stdin.readline())
    for inp in sys.stdin.readlines():
        inp = inp.split()
        if inp[0] == "insert":
            tree.insert(int(inp[1]))
        else:
            tree.print()

Submission status: Accepted

Solution code:
import sys

def main():
    n = input()
    tree = MyBinaryTree(n)
    for i in range(n):
        cmd = map(str,raw_input().split())
        if cmd[0] == "insert":
            insert(tree,MyNode(int(cmd[1])))
        elif cmd[0] == "print":
            tree.inorder(tree.root)
            print ""
            tree.preorder(tree.root)
            print ""
    
    
class MyBinaryTree():
    def __init__(self,num_nodes):
        self.root = None

    def preorder(self,node):
        sys.stdout.write(" {}".format(node.key))
        l = node.left
        r = node.right
        if l is not None:
            self.preorder(l)
        if r is not None:
            self.preorder(r)    

    def inorder(self,node):
        l = node.left
        r = node.right
        if l is not None:
            self.inorder(l)
        sys.stdout.write(" {}".format(node.key))
        if r is not None:
            self.inorder(r)


def insert(T,z):
    y = None
    x = T.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:
        T.root = z
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:

import sys

class Node:
    def __init__(self, value, p = None, l = None, r = None):
        self.key = value
        self.p = p
        self.left = l
        self.right = r

def getroot(x):
    if x.p != None:
        return getroot(x.p)
    return x

def preorder(x, A):
    if x == None:
        return
    A.append(x.key)
    preorder(x.left, A)
    preorder(x.right, A)

def inorder(x, A):
    if x == None:
        return
    inorder(x.left, A)
    A.append(x.key)
    inorder(x.right, A)

def postorder(x, A):
    if x == None:
        return
    postorder(x.left, A)
    postorder(x.right, A)
    A.append(x.key)

def ptree(root):
    pre = [""]
    ino = [""]
    preorder(root, pre)
    inorder(root, ino)
    print(" ".join(map(str,ino)))
    print(" ".join(map(str,pre)))

def insert(Tree, root, z):
    y = None # x ??????
    x = root  # 'T ??????'
    while x != None:
        y = x # ???????¨????
        if z.key < x.key:
            x = x.left # ?????????????§????
        else:
            x = x.right # ?????????????§????
    z.p = y

    Tree.append(z)
    if y == None: # T ???????????´???
        return z
    elif z.key < y.key:
        y.left = z # z ??? y ?????????????????????
    else:
        y.right = z # z ??? y ?????????????????????
    return root

def main():

    """ ????????? """
    num = int(input().strip())
    istr = sys.stdin.read()
    cmds = list(istr.splitlines())
    Tree = []
    root = None
    for i in range(num):
        cmd = cmds[i][0]
        if cmd == "i":
            n = Node(int(cmds[i][7:]))
            root = insert(Tree, root, n)
        elif cmd == "p":
            ptree(root)
    

if __name__ == '__main__':
    main()

Submission status: Accepted

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.inorder(node.left)
        print(" {}".format(node.key), end = "")
        if node.right:
            self.inorder(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: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(100000)

def insert(k, node):
    if k < node:
        if tree[node]["left"] == None:
            tree[node]["left"] = k
            tree[k] = {"parent": node, "left": None, "right": None}
            return
        else:
            insert(k, tree[node]["left"])
    else:
        if tree[node]["right"] == None:
            tree[node]["right"] = k
            tree[k] = {"parent": node, "left": None, "right": None}
            return
        else:
            insert(k, tree[node]["right"])


def pre_order(n):
    result = []
    if n == None:
        return []
    result.append(str(n))
    result.extend(pre_order(tree[n]["left"]))
    result.extend(pre_order(tree[n]["right"]))
    
    return result


def in_order(n):
    result = []
    
    if n == None:
        return []

    result.extend(in_order(tree[n]["left"]))
    result.append(str(n))
    result.extend(in_order(tree[n]["right"]))
    
    return result


M = int(input())
root = "nan"
while root == "nan":
    inp = [n for n in input().split()]
    if inp[0] == "print":
        print()
        print()
    else:
        root = int(inp[1])

tree = {root:{"parent": None, "left": None, "right": None}}

for i, _ in enumerate(range(M-1)):
    inp = [n for n in input().split()]
    if inp[0] == "print":
        in_text = ""
        pre_text = ""
        print(" " + " ".join(in_order(root)))
        print(" " + " ".join(pre_order(root)))
    else:
        insert(int(inp[1]), root)
        #if i%1000 == 0:
        #    print("done {}/{}".format(i, M))

Submission status: Accepted

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


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

    def insert(self, key):
        root_node = self.root
        insert_node = Node(key)
        parent_node = None

        while root_node:
            parent_node = root_node
            if insert_node.key < root_node.key:
                root_node = root_node.left
            else:
                root_node = root_node.right

        insert_node.parent = parent_node

        if parent_node is None:
            self.root = insert_node
        elif insert_node.key < parent_node.key:
            parent_node.left = insert_node
        else:
            parent_node.right = insert_node

    def show_preorder(self, node):
        node_list = []

        node_list.append(node.key)
        if node.left is not None:
            node_list.extend(self.show_preorder(node.left))
        if node.right is not None:
            node_list.extend(self.show_preorder(node.right))

        return node_list

    def show_inorder(self, node):
        node_list = []

        if node.left is not None:
            node_list.extend(self.show_inorder(node.left))
        node_list.append(node.key)
        if node.right is not None:
            node_list.extend(self.show_inorder(node.right))

        return node_list

    def print(self):
        print(' ' + ' '.join(map(str, self.show_inorder(self.root))))
        print(' ' + ' '.join(map(str, self.show_preorder(self.root))))


if __name__ == '__main__':
    tree = BinarySearchTree()

    n = int(input())

    for i in range(n):
        command = input().split()

        if command[0] == 'insert':
            tree.insert(int(command[1]))
        elif command[0] == 'print':
            tree.print()

Submission status: Accepted

Solution code:
m = int(input())

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


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

    def getRoot(self):
        return self.root
    def setRoot(self, v):
        self.root = v

    def inorder(self, v=None):
        if v is None:
            v = self.root
        if v.left is not None:
            self.inorder(v.left)
        print(' ' + str(v.key), end='')
        if v.right is not None:
            self.inorder(v.right)
        
    def preorder(self, v=None):
        if v is None:
            v = self.root
        print(' ' + str(v.key), end='')
        if v.left is not None:
            self.preorder(v.left)
        if v.right is not None:
            self.preorder(v.right)

def insert(T, z):
    y = None
    x = T.getRoot()
    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:
        T.setRoot(z)
    elif z.key < y.key:
        y.left = z
    else:
        y.right = z

def find(T, k):
    x = T.getRoot()
    while x is not None:
        if x.key == k:
            print('yes')
            return
        elif x.key < k:
            x = x.right
        else:
            x = x.left
    print('no')


T = BinaryTree()

for i in range(m):
    inp = input().split()
    if inp[0] == 'print':
        T.inorder()
        print()
        T.preorder()
        print()
    elif inp[0] == 'find':
        find(T, int(inp[1]))
    else:
        v = Node(int(inp[1]), None, None)
        insert(T, v)

Submission status: Accepted

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

    def insert(self, insert_node):
        p = None
        r = self.root
        while r:
            p = r
            if insert_node.value < r.value:
                r = r.left
            else:
                r = r.right

        if not p:
            self.root = insert_node
        elif insert_node.value < p.value:
            p.left = insert_node
        else:
            p.right = insert_node

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

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.value, end="")
        if l:
            l.pre_order_search()
        if r:
            r.pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l:
            l.in_order_search()
        print("",self.value, end="")
        if r:
            r.in_order_search()

m = int(input())
tree = BinaryTree()

for i in range(m):
    inp = input().split()
    if inp[0] == "insert":
        tree.insert(Node(int(inp[1]), None, None))
    else:
        tree.root.in_order_search()
        print()
        tree.root.pre_order_search()
        print()

Submission status: Accepted

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

    def insert(self, x):
        node = self.Node(x)
        if self.root is None:
            self.root = node
        else:
            here = self.root
            #
            temp = None
            while here is not None:
                temp = here
                if x < here.node:
                    here = here.left
                elif x > here.node:
                    here = here.right
            if x < temp.node:
                temp.left = node
            elif x > temp.node:
                temp.right = node

    def inorder(self, answer, address = "root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        self.inorder(answer, address.left)
        answer.append(address.node)
        self.inorder(answer, address.right)

    def preorder(self, answer, address = "root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        answer.append(address.node)
        self.preorder(answer, address.left)
        self.preorder(answer, address.right)

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

query = int(input())
bt = BinarySearchTree()
for _ in range(query):
    command = input()
    if command[0] == "i":
        bt.insert(int(command.split(" ")[1]))
    else:
        a = []
        bt.inorder(a)
        print(" ", end = "")
        print(*a)
        a = []
        bt.preorder(a)
        print(" ", end = "")
        print(*a)

Submission status: Accepted

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


class Node(object):
    __slots__ = ["value", "left", "right"]

    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


class BinTree(object):
    def __init__(self):
        self._tree = None

    def insert(self, value):
        parent = None
        current = self._tree

        while current is not None:
            parent = current
            if value < current.value:
                current = current.left
            else:
                current = current.right

        if parent is None:
            self._tree = Node(value)
        elif value < parent.value:
            parent.left = Node(value)
        else:
            parent.right = Node(value)

    def preoder_walk(self):
        def preoder(node):
            result = []
            if node is None:
                pass
            else:
                result.append(node.value)
                result.extend(preoder(node.left))
                result.extend(preoder(node.right))
            return result

        return preoder(self._tree)

    def inorder_walk(self):
        def inorder(node):
            result = []
            if node is None:
                pass
            else:
                result.extend(inorder(node.left))
                result.append(node.value)
                result.extend(inorder(node.right))
            return result

        return inorder(self._tree)


def print_tree(tree):
    print(" " + " ".join([str(val) for val in tree.inorder_walk()]))
    print(" " + " ".join([str(val) for val in tree.preoder_walk()]))


def insert_main(commands):
    tree = BinTree()
    for com in commands:
        if com[0] == "insert":
            tree.insert(int(com[1]))
        elif com[0] == "print":
            print_tree(tree)
        else:
            raise ValueError


if __name__ == "__main__":
    n = int(input())
    commands = [com.split() for com in sys.stdin.readlines()]
    insert_main(commands)