1

我希望有人可以帮助我,我不是编程专业人士,但正在使用 Python 来学习和试验二叉树。

下面是我拥有的代码,并尝试尝试在其节点中存储对节点父节点的引用,但其父节点的存储不适用于叶节点。在构建树的过程中有没有办法做到这一点?

我还想知道给定节点是“左”还是“右”节点。我认为当节点存储在 TreeNode.left 或 TreeNode.right 的实例中时,我可能能够在 Python 中获得对此的引用,如n._ name _或类似的东西。你能告诉我找到一个节点是左还是右的正确方法吗?

我的最终目标是通过水平顺序遍历来可视化我的树。

class TreeNode:
 left, right, data = None, None, 0

def __init__(self,nodeData, left = None, right = None, parent = None):
 self.nodeData = nodeData
 self.left = left
 self.right = right
 self.parent = self

class Tree:
 def __init__(self):
  self.root = None

 def addNode(self, inputData):
  return TreeNode(inputData)

 def insertNode(self, parent, root, inputData):
  if root == None:
   return self.addNode(inputData)
  else:
   root.parent = parent
   if inputData <= root.nodeData:
    root.left = self.insertNode(root, root.left, inputData)
   else:
    root.right = self.insertNode(root, root.right, inputData)
   return root
4

1 回答 1

3

这有很多很多事情是错误的。既然是作业,我会提供一个提示。

def __init__(self,nodeData, left = None, right = None, parent = None):
 self.nodeData = nodeData
 self.left = left
 self.right = right
 self.parent = self

为什么不self.parent设置为parent

于 2012-02-08T10:52:17.107 回答