You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二叉树中缀/后缀遍历遇TypeError参数不匹配问题求助

问题解决:二叉树中序/后序遍历的TypeError修复

错误原因分析

你遇到的TypeError: Node.Postfix() takes 1 positional argument but 2 were given,核心问题有两个:

  • 实例方法Postfix定义时仅接收self参数,但调用时错误传入了self.left作为额外参数
  • 方法内错误使用Node类名代替实例self来访问属性和判断节点存在性

修正后的完整代码实现

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

    # 后序遍历:左 -> 右 -> 根
    def Postfix(self):
        if self.left:
            self.left.Postfix()
        if self.right:
            self.right.Postfix()
        print(self.val, end=" ")

    # 中序遍历:左 -> 根 -> 右
    def Infix(self):
        if self.left:
            self.left.Infix()
        print(self.val, end=" ")
        if self.right:
            self.right.Infix()

    # 栈构建表达式二叉树的类方法
    @classmethod
    def constructTree(cls, expr):
        stack = []
        tokens = expr.split()
        for token in tokens:
            # 操作符:弹出两个节点作为左右子树
            if token in "+-*/":
                node = cls(token)
                node.right = stack.pop()
                node.left = stack.pop()
                stack.append(node)
            # 操作数:直接入栈
            else:
                stack.append(cls(token))
        return stack.pop()

# 测试
X="- + a b * * e f g"
r = Node.constructTree(X)

print("后序遍历结果:")
r.Postfix()  # 输出:a b + e f * g * -
print("\n中序遍历结果:")
r.Infix()    # 输出:a + b - e * f * g

关键修正点

  • 递归调用遍历方法时,直接通过子节点实例调用(self.left.Postfix()),而非给当前实例的方法传参数
  • 判断节点是否存在时,直接检查self.left/self.right是否非空,而非判断类Node
  • 访问节点值时使用实例属性self.val,而非类属性Node.val
  • 补充了栈构建二叉树的constructTree方法,确保逻辑完整

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:05:58