You are given an acyclic, undirected, connected graph in which each vertex has at most 3 neighbours. You have to find out whether the graph can also be a valid binary tree, and if yes, then return the index of the vertex which can be used as the root of the tree. Otherwise, return -1.
Example:
graph = [[1],[0,2,3],[1],[1,4],[3]]
Now each vertex is black or white. Find a root so it's a valid binary tree, same-depth vertices share a color, and colors alternate between layers. So, your tree's levels should look like either black->white->black->white or white->black->white->black. Return -1 if none.
Example:
graph = [('black',[1]),('white',[0,2,3]),('black',[1]),('black',[1,4]),('white',[3])]
Now we have three colors (red, white, black) that must follow the fixed cycle red → white → black → red as depth increases. Root can be any color. Return -1 if none.
Example:
graph = [('black',[1]),('red',[0,2,3]),('white',[1]),('white',[1,4]),('black',[3])]
Discussion
Loading comments…