Dec-06-2022, 09:28 PM
let said that I get a randomly created array of 12 numbers for this tree below instead of having the number picked by me, should I hand-pick the root? or should I let it be one of the random numbers of the array? I asking this is because I just don't want that by change the tree end up without a number on one of the sides(left or right). For example, let said the random array gives me this list 1-2-3-4-5-6-7-8-9-10 and the program choose 1 as the root I only going to get numbers on the right side. I guess I could just get the mean of the list and use int no to get decimals? or is there an easier way?
class Node: def __init__(self, data): self.data = data self.leftChild = None self.rightChild = None def insert(self, data): if data < self.data: if self.leftChild: self.leftChild.insert(data) else: self.leftChild = Node(data) return else: if self.rightChild: self.rightChild.insert(data) else: self.rightChild = Node(data) return def PrintTree(self): if self.leftChild: self.leftChild.PrintTree() print( self.data), if self.rightChild: self.rightChild.PrintTree() root = Node(27) root.insert(28) root.insert(30) root.insert(26) root.insert(22) root.insert(18) root.insert(17) root.insert(14) root.insert(35) root.insert(31) root.insert(10) root.insert(19) root.PrintTree()
Output:10
14
17
18
19
22
26
27
28
30
31
35
Process finished with exit code 0