Yahoo Interview Question: Find a longest path in a tree... | Glassdoor

Interview Question

Software Engineer Interview Santa Clara, CA

Find a longest path in a tree.

Answer

Interview Answer

1 Answer

0

List longestPath(Node node) {
    List path = new ArrayList();
    path.add(node);

    List longestChildPath = new ArrayList();
    for(Node child: node.children()) {
        List childPath = longestPath(child);
        if (longestChildPath == null || childPath.size() > longestChildPath) {
            longestChildPath = childPath;
        }
    }

    path.addAll(longestChildPath);
    return path;
}

Anonymous on Jul 14, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.