python - 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))
解决方案
检查内联评论。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]
推荐阅读
- c - 为什么这会产生分段错误?
- android - 与 Dialog Fragment 结合使用时,Toast 出现较晚
- r - 循环遍历字符和数字以创建变量
- java - 当java线程执行同步语句失败时会发生什么?
- webpack - pnotify 不能在我的 symfony 4 和 webpack 中使用 yarn
- mysql - 如何在包含 := 运算符的 VB.NET10 中执行此 mysql 查询
- java - ControlsFX 和 Java 11 无法运行采样器
- javascript - 如何绘制与红色块相同的图像
- row - Understrap/Bootstrap:.row-equal-height 不适用于等高列?
- excel - 条件格式化多行