class
Node:
def
__init__(
self
, key):
self
.key
=
key
self
.left
=
None
self
.right
=
None
class
BST:
def
__init__(
self
):
self
.root
=
None
def
create_node(
self
, key):
return
Node(key)
def
insert(
self
, root, key):
if
root
is
None
:
return
self
.create_node(key)
if
key < root.key:
root.left
=
self
.insert(root.left, key)
elif
key > root.key:
root.right
=
self
.insert(root.right, key)
return
root
def
copy_tree(
self
, root):
if
root
is
None
:
return
None
new_node
=
self
.create_node(root.key)
new_node.left
=
self
.copy_tree(root.left)
new_node.right
=
self
.copy_tree(root.right)
return
new_node
def
make_persistent(
self
, key):
new_bst
=
BST()
new_bst.root
=
self
.copy_tree(
self
.root)
new_bst.root
=
new_bst.insert(new_bst.root, key)
return
new_bst
def
print_in_order(
self
, root):
if
root
is
not
None
:
self
.print_in_order(root.left)
print
(root.key, end
=
" "
)
self
.print_in_order(root.right)
if
__name__
=
=
"__main__"
:
bst1
=
BST()
bst1.root
=
bst1.insert(bst1.root,
50
)
bst1.root
=
bst1.insert(bst1.root,
30
)
bst1.root
=
bst1.insert(bst1.root,
20
)
bst1.root
=
bst1.insert(bst1.root,
40
)
bst1.root
=
bst1.insert(bst1.root,
70
)
bst1.root
=
bst1.insert(bst1.root,
60
)
bst1.root
=
bst1.insert(bst1.root,
80
)
bst2
=
bst1.make_persistent(
55
)
print
(
"BST1: "
, end
=
"")
bst1.print_in_order(bst1.root)
print
()
print
(
"BST2: "
, end
=
"")
bst2.print_in_order(bst2.root)
print
()