双亲存储结构下树中node.parent=self
时间: 2023-09-24 10:09:02 浏览: 47
双存储结构是一种树的存储方式,它通过在每个节点中增加一个指向其父节点的指针来表示树的结构。在这种存储方式下,每个节点都保存了一个指向其父节点的指针,因此可以方便地从子节点访问到其父节点。
在双亲存储结构中,对于每个节点来说,它的父节点的指针就是它的parent属性。因此,当我们创建一个节点时,可以将该节点的parent属性设置为自身,表示该节点是根节点。当我们插入一个节点时,可以将该节点的parent属性设置为插入节点的父节点,以建立父子关系。
例如,假设我们要创建一棵包含5个节点的树,可以先创建根节点,然后逐个插入子节点,并设置每个节点的parent属性。具体操作如下:
```
class TreeNode:
def __init__(self, val=None):
self.val = val
self.parent = self # 将根节点的parent属性设置为自身
self.children = []
root = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
root.children = [node2, node3]
node2.parent = root # 设置node2的父节点为root
node3.parent = root # 设置node3的父节点为root
node2.children = [node4]
node3.children = [node5]
node4.parent = node2 # 设置node4的父节点为node2
node5.parent = node3 # 设置node5的父节点为node3
```
在上面的代码中,我们先创建了一个根节点root,并将其parent属性设置为自身。然后依次创建节点2到节点5,并设置它们的parent属性。最后,我们通过将子节点添加到父节点的children列表中来建立父子关系。