如果用户在Python二叉树中输入错误的搜索数据,则返回错误

时间:2016-05-14 04:47:27

标签: python

我尝试将用户输入数据附加到现有树中,但我的代码似乎无法正常工作,因为当我再次搜索新数据时(我将该部分删除)丢失了。我真的很陌生,有人可以帮帮我吗?

class BinTreeNode(object):

    def __init__(self, value, value2):
        self.value=value
        self.value2=value2

        self.left=None
        self.right=None


def tree_insert( tree, item,value):
    if tree==None:
        tree=BinTreeNode(item, value)
    else:
        if(item < tree.value):
            if(tree.left==None):
                tree.left=BinTreeNode(item,value)
            else:
                return tree_insert(tree.left,item, value)
        else:
            if(tree.right==None):
                tree.right=BinTreeNode(item,value)
            else:
                return tree_insert(tree.right,item,value)
    return tree

def search(value,p):
    if p is None:
        return 1

    elif(p.val == value):
        print("You bought item no:",p.value,", the description",     p.value2 )
    else:
        if(p.val !=None):
            if(p.val < value):
                return search (value,p.right)
            if(p.val > value):
                return search (value,p.left)

t=tree_insert(None,13,3)
tree_insert(t,10,3)
tree_insert(t,5,3)
tree_insert(t,2,3)

option = int(input("Please enter code:"))
answer = search(option,tree)

while (answer == 1):
    print("You've entered a wrong option")
    option = int(input("Please enter code:"))
    answer = search(option,tree)

0 个答案:

没有答案