首页 > 解决方案 > Python AttributeError:'builtin_function_or_method'对象没有属性'right'

问题描述

有人可以帮帮我吗?在这段代码中,我正在做 Iterative Postorder Traversal,但我不知道为什么会出现这个错误。在下面给出的树结构中,它打印 1,2,4 之后它会给出以下错误:

AttributeError: 'builtin_function_or_method' object has no attribute 'right'

class TreeNode:
   def __init__(self, x):
       self.val = x
       self.left = None
       self.right = None

def peek(stack):
    if len(stack) > 0:
        return stack[-1]
    return None

def postorderTraversal(root):
    s = []
    ans = []
    while True:
        if root is not None:
            if root.right is not None:
                s.append(root.right)
            s.append(root)
            root = root.left
        else:
            p = s.pop()
            if p.right == s[-1]:
                q = s.pop
                s.append(p)
                root = q
            else:
                ans.append(p.val)
                root = None
        if len(s) == 0:
            break
    return ans

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)

print(postorderTraversal(root))

标签: python

解决方案


检查内联评论。s.pop代表 <built-in method pop of list object at 0x100e2c050>对象而不是你的对象class TreeNode

class TreeNode:
   def __init__(self, x):
       self.val = x
       self.left = None
       self.right = None

def peek(stack):
    if len(stack) > 0:
        return stack[-1]
    return None

def postorderTraversal(root):
    s = []
    ans = []
    while True:
        if root is not None:
            if root.right is not None:
                s.append(root.right)
            s.append(root)
            root = root.left
        else:
            p = s.pop()
            if s and p.right == s[-1]: ##### Error2 check if s is not empty if true check for p.right match
                q = s.pop() ##### Error1
                s.append(p)
                root = q
            else:
                ans.append(p.val)
                root = None
        if len(s) == 0:
            break
    return ans

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)

print(postorderTraversal(root))

Outputs: [4, 5, 2, 6, 7, 3, 1]


推荐阅读