| layout | page |
|---|
BiNode: Consider a simple data structure called BiNode, which has pointers to two other nodes,
publicclassBiNode {
publicBiNodenode1, node2;
publicintdata;
}The data structure BiNode could be used to represent both a binary tree (where node1 is the left node and node2 is the right node) or a doubly linked list (where node1 is the previous node and node2 is the next node). Implement a method to convert a binary search tree (implemented with BiNode) into a doubly linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure).
classBiNode:
def__init__(self, left, right, data):
self.left=leftself.right=rightself.data=datadef__str__(self):
returnf"node: left={self.left} self={self.data} right={self.right}"defprint_linked_list(self):
cur_node=selfwhilecur_node.left:
cur_node=cur_node.leftwhileTrue:
print(cur_node.data, " ", end="")
ifcur_node.right:
cur_node=cur_node.rightelse:
breakdefbst_2_linked_list(cur_node: BiNode, left_link: BiNode, right_link: BiNode):
ifcur_node.left:
bst_2_linked_list(cur_node.left, left_link, cur_node)
elifleft_link:
cur_node.left=left_linkleft_link.right=cur_nodeifcur_node.right:
bst_2_linked_list(cur_node.right, cur_node, right_link)
elifright_link:
cur_node.right=right_linkright_link.left=cur_nodeif__name__=="__main__":
n4=BiNode(None, None, 4)
n0=BiNode(None, n4, 0)
n13=BiNode(None, None, 13)
n14=BiNode(n13, None, 14)
n12=BiNode(None, n14, 12)
n16=BiNode(n12, None, 16)
n8=BiNode(n0, n16, 8)
n28=BiNode(None, None, 28)
n32=BiNode(n28, None, 32)
n52=BiNode(None, None, 52)
n48=BiNode(None, n52, 48)
n40=BiNode(n32, n48, 40)
n24=BiNode(n8, n40, 24) # rootbst_2_linked_list(n24, None, None)
n24.print_linked_list()firstNode=Noneprev=NonedefinOrder(node):
ifnodeisNone:
returninOrder(node.node1)
visit(node)
inOrder(node.node2)
defvisit(node):
globalprev, firstNodeifprevisNone:
firstNode=nodeelse:
prev.node2=nodenode.node1=prevprev=nodedefsweepRight(node):
a=Noneb=NoneifnodeisNone:
returnifnode.node1isnotNone:
a=node.node1.dataifnode.node2isnotNone:
b=node.node2.dataprint(f"Node: {node.data}, Prev: {a}, Next: {b}")
sweepRight(node.node2)
if__name__=="__main__":
inOrder(tree)
sweepRight(firstNode)