C
C
Carzil2011-08-15 19:49:58
Python
Carzil, 2011-08-15 19:49:58

BST, what and how?

Good afternoon! There is a task: to sort N elements, using a binary search tree. If the element is already in the tree, then it is not necessary to add it. I do like this:

#!/usr/bin/python
#© Andreev Alexander (aka Carzil) 2011
class Node(object):
    def __init__(self, key, left, right):
        self.key = key
        self.left = left
        self.right = right
        
        
    def set_value(self, val):
        self.key = val
    
class Tree(object):
    def __init__(self):
        self.root = None
        
    def add_key(self, node, val):
        if node == None:
            return Node(val, None, None)
        elif val < node.key:
            return Node(node.key, self.add_key(node.left, val), node.right)
        elif val > node.key:
            return Node(node.key, node.left, self.add_key(node.right, val))
        else:
            return Node(node.key, node.left, node.right)
                            
                
    def insert(self, val):
        self.root = self.add_key(self.root, val)
        
    def traverse(self, node):
        global cnt
        if node == None:
            return
        else:
            cnt += 1
            self.traverse(node.left)
            self.traverse(node.right)
            
    def inorder_(self, node):
        if node != None:
            self.inorder_(node.left)
            print(node.key, end=" ")
            self.inorder_(node.right)
            
    def inorder(self):
        self.inorder_(self.root)
            
t = Tree()
for i in input().split():
    if i == "0":
        break 
    t.insert(int(i))
t.inorder()

But, when submitting it to the testing system, it says that the answer is wrong on 37 out of 60 tests. What could be the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vas3K, 2011-08-15
@Vas3K

Either something is wrong with the output, or you can rest against the maximum depth of the recursion, the insert code is correct at first glance. Need more info. What are the input restrictions?

@
@ntkt, 2011-08-16
_

Got stuck in recursion. The first code crashed at 1100 elements. This one doesn't work that way.

@
@ntkt, 2011-08-17
_

And in the task it was definitely said to remove duplicates when sorting? :) And, as a rule of good manners, it's better to wrap the code that is at the top level and not included in the classes in a view condition: so that your classes can be quickly imported without dealing with this code at the top level.
[04:26][email protected]:~/temp$ ./bst.py
'1 3 3 2 5 4 5'
1
2
3
4
5

...
class ...
...
if __name__=='main':
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question