为什么输出总是空集

时间:2019-12-23 10:12:37

标签: python binary-tree

问题是我有一棵树,其中的运算符是某些节点的键,而子节点是整数,我应该遍历树并返回答案,如果我的解释很不好意思,那么ss应该是一些,但总是返回空,但是如果只有两个孩子,则意味着只有根并且是孩子,它可以正常工作

class node : 
        def __init__(self , key ):
            self.key = key 
            self.left = None
            self.right = None 
    class binarytree :
        def __init__(self ):
            self.root = None

        def  evaltree(self , root ) :
            root = self.root         
            q = []
            q.append(root)
            ss = []
            for X in range(len(q)) : 
                z = q[0]
                x = z.left
                y = z.right
                if isinstance(x.key , int ) == True and isinstance(y.key , int) == True : 
                    if z.key == "+" : 
                        sums = x.key + y.key
                        ss.append(sums) 
                        break

                    if z.key == "-" :  
                        print(x.key)
                        sums = x.key - y.key
                        ss.append(sums) 
                        break

                    if z.key == "*" : 
                        sums = x.key * y.key
                        ss.append(sums)
                        break 

                    if z.key == "/" : 
                        sums = x.key / y.key 
                        ss.append(sums) 
                        break

                    if isinstance(x.key , int) == False and isinstance(y.key , int ) == False  : 
                        q.append(x) 
                        q.append(y)
                        break         
            return ss
    nll = binarytree()
    nll.root= node("+")
    root = nll.root
    r= node("/")
    u = node("*")
    root.left = r
    root.right = u
    ten = node(10)
    fi = node(5)
    twe = node(20)
    two = node(2)
    r.left = ten
    r.right = fi
    u.left = twe 
    u.right = two 
    n =  nll.evaltree(root) 
    print(n)

0 个答案:

没有答案