Binary Tree Random Node with Python Code (part 1)
Photo by Javier Quesada on Unsplash
Random Node
From the book - Cracking the Coding Interview (4.11). Build a binary tree class along with the insert, delete, find and the getRandomNode method which returns a random node in the tree. (All nodes shall have the same possibility to be returned.)
Brute Force
The intuition brute force solution would be to traverse all nodes and collect them into an array/list then randomly choose one of them out of Uniform Distribution.
Time: O(n)
Space: O(1)
Optimized
Though it would be nicer if we can give a O(1) method. Since we are given the ownership of the whole class (generated from the scratch), we can simply record the size in order to produce a uniform random choice.
Record the Size in Node
|
|
Then update the insert and the delete function. The delete function would be a bit tricky to implement.
The solution provided by the book outsource github isn’t quite right on the delete function. (The size property wasn’t being taken care of quite right.)
|
|