二叉搜索树 - 存储对父节点的引用
我希望有人可以帮助我,我不是编程专业人士,但正在使用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
I hope someone can help me, I'm not a programming professional, but am using Python to learn and experiment with binary trees.
Below is the code I have, and have attempted to try and store a reference to a node's parent in it's node, the storing of it's parent node, won't work for leaf nodes though. Is there a way of doing this during the process of building the tree?
I'd also like to know for a given node, whether is's a 'Left or 'Right' node. I thought seeing as the node is stored in an instance of TreeNode.left or TreeNode.right, I might be able to get a reference to this in Python, as in n._name_ or something like that. Could you tell me the correct way to find whether a node is left or right?
My ultimate goal will be to visualise my tree through a level order traversal.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这有很多很多问题。既然是作业,我就提供一个提示。
为什么
self.parent
没有设置为parent
?There are many, many things wrong with this. Since it's homework, I'll supply one hint.
Why isn't
self.parent
set toparent
?