返回

python-访问二叉树的最大递归错误

发布时间:2022-09-06 08:36:45 260
# node.js

我是一名 Python 新手,试图创建一个计算器程序,该程序采用后缀方程返回一个二叉树堆栈对象,然后使用下面的代码格式返回一个中序方程。我的二进制类和树函数似乎正在工作并返回值。但是当使用 inorder 函数时,我得到重复的最大递归错误。任何帮助,将不胜感激!工作二进制类,但以防万一您需要以下代码中调用的函数的上下文:

输入 make_tree: '5 2 3 * +'.split() 我想要返回的内容: (5+(2*3))

class BinaryTree:

    def __init__(self,rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None
    def insertLeft(self,newNode):
        if self.leftChild == None:
            self.leftChild = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.leftChild = self.leftChild
            self.leftChild = t
    def insertRight(self,newNode):
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.rightChild = self.rightChild
            self.rightChild = t
    def getRightChild(self):
        return self.rightChild
    def getLeftChild(self):
        return self.leftChild
    def setRootVal(self,obj):
        self.key = obj
    def getRootVal(self):
        return self.key
    def __str__(self):
        s = f"{self.key}"
        if self.leftChild != None:
            s += str(self.leftChild)
        if self.rightChild != None:
            s += str(self.rightChild)
        return s
     def make_tree(postfix):
        stack = Stack()
        IsOperator = '+/*-'
        # Traverse through every character of input expression
        kiln = ''.join(postfix)
        for char in kiln:
            # if operand, simply push into stack
            if char not in IsOperator:
                t = BinaryTree(char)
                stack.items.append(t)
                # Operator
            else:
                # Pop two top nodes
                t = BinaryTree(char)
                t1 = stack.pop()
                t2 = stack.pop()

                # make them children
                t.rightChild = t1
                t.leftChild = t2

                # Add this subexpression to stack
                stack.items.append(t)

                # Only element  will be the root of expression tree
        return t

    def __str__(self):
        return ExpTree.inorder(self) ```

My Binary Tree creator is working well but when trying to preorder I am getting errors.
def inorder(self):
    stack = Stack()
    b = BinaryTree
    e = ExpTree
    if tree != []:
        e.inorder(b.getLeftChild(tree))
        print(b.getRootVal(tree))
        e.inorder(b.getRightChild(tree))
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像