问题是,给定一个二叉树,其中每个节点有四个数据:left
,right
,data
和一个空指针{parent
指针指向其父节点(根父指针自然指向空值)。现在我该怎么做?我尝试过这样的后序遍历:
last = None
def mypostorder(root):
if root:
mypostorder(root.left)
mypostorder(root.right)
if last:
last.parent = root
last = root
但显然它不起作用,我知道为什么在更新左子元素的parent
指针后,它将其设置为last
,所以下次当它访问右子对象(它的兄弟姐妹)时,它会将它的parent
设置为左子对象。如何调整它以获得正确的结果?有没有可能用堆栈迭代的方式来实现呢?在
初始调用:
setParent(root,NULL);
你走错了路。我认为你的解决方案会使一个节点的父节点指向它的子节点
试试看:
相关问题 更多 >
编程相关推荐