Skip to content

Instantly share code, notes, and snippets.

@anilpai
Created February 3, 2020 22:33
Show Gist options
  • Save anilpai/26a49a9faeb552f0d6eb3a85140b9045 to your computer and use it in GitHub Desktop.
Save anilpai/26a49a9faeb552f0d6eb3a85140b9045 to your computer and use it in GitHub Desktop.
algo to clone a graph
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_a_tree():
root = TreeNode(10)
a = TreeNode(20)
b = TreeNode(30)
c = TreeNode(40)
d = TreeNode(50)
root.left = a
root.right = b
a.right = c
b.left = d
return root
def clone_tree(root):
"""clone a tree without any random pointers"""
if root is None:
return None
new_root = TreeNode(root.value)
new_root.left = clone_tree(root.left)
new_root.right = clone_tree(root.right)
return new_root
"""driver program"""
root = build_a_tree()
new_root = clone_tree(root)
print(new_root.value)
print(new_root.left.value)
print(new_root.right.value)
print(new_root.left.right.value)
print(new_root.right.left.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment