Nodes and Trees | Python

April 13th, 2021 07:47:15 PM

					
import random class Node: def __init__(self, c): self.left = None self.right = None self.color = c def SetColor(self,c) : self.color = c def PrintNode(self) : print(self.color) def insert(s, root, i, n): if i < n: temp = Node(s[i]) root = temp root.left = insert(s, root.left,2 * i + 1, n) root.right = insert(s, root.right,2 * i + 2, n) return root def MakeTree(s) : list = insert(s,None,0,len(s)) return list def MakeSet() : s = [] count = random.randint(7,12) for _ in range(count) : color = random.randint(0,1) == 0 and "Red" or "White" s.append(color) return s def ChangeColor(root) : if (root != None) : if (root.color == "White") : root.SetColor("Red") ChangeColor(root.left) ChangeColor(root.right) def PrintList(root) : if root.left != None : PrintList(root.left) else : root.PrintNode() if root.right != None : PrintList(root.right) else : root.PrintNode() t1 = MakeTree(MakeSet()) print("Original Colors For Tree 1:\n") PrintList(t1) ChangeColor(t1) print("New Colors For Tree 1:\n") PrintList(t1) t2 = MakeTree(MakeSet()) print("Original Colors For Tree 2:\n") PrintList(t2) ChangeColor(t2) print("New Colors For Tree 2:\n") PrintList(t2) t3 = MakeTree(MakeSet()) print("Original Colors For Tree 3:\n") PrintList(t3) ChangeColor(t3) print("New Colors For Tree 3:\n") PrintList(t3)

Featured Posts