Amazon Interview Question
SDE1sCountry: United States
Java
public boolean isUnivalTree (TreeNode root)
{
int value = root.children.isEmpty() ? root.val : root.children.get(0).val;
boolean result = true;
if (root==null) return false;
for (TreeNode node : root.children)
{
result = result & (node.val==value) & isUnivalTree(node);
}
return result;
}
First Approach: Perform a dfs or bfs on the tree and retrieve the results. Check whether all of them are the same element. Second approach: As you are traversing, use a set or hash map to make sure they are all the same elements and if they are different return False.
Simple solution in Python outlining the first approach:
Test code:
- prudent_programmer April 04, 2018