Google Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
A quad tree can have only 3 color of nodes .. black white and gray
The crux is that at each level(depth) if the pixel color is not gray then it represents 4^(k-d) pixels of color same as itself. where k represents the overall size of image of size (2^k X 2^k) and d represents the current depth of node in the tree
Assuming each node has color field: "black"/"white"/"gray"
and 4 field for the 4 child nodes of type node: ne , nw, se, sw
Code in Python:
def quadTreeCountBlackPixels(root, depth, size):
if (None == root):
return 0
if (root.color == “white”):
return 0
elif (root.color == “black”):
return pow(4, size-depth)
else:
seCount = quadTreeCountBlackPixels(root.se, depth+1, size)
swCount = quadTreeCountBlackPixels(root.sw, depth+1, size)
neCount = quadTreeCountBlackPixels(root.ne, depth+1, size)
nwCount = quadTreeCountBlackPixels(root.nw, depth+1, size)
return seCount + swCount + neCount +nwCount
#initial call to function
totalBlackPixels = quadTreeCountBlackPixels(root, 0 , k):
#where the image is of size 2^k X 2^k
Consider that edge nodes are either black or white in Q tree. If your node edge is at depth d, it corresponds to S/2^(2d) pixels, when S is total number of pixels in image, So you can traverse through tree and find total black pixels
- Anonymous September 28, 2013