您的位置:首页 > 其它

CareerCup Find the diameter of the tree

2014-03-08 18:58 393 查看
Given a tree in the form of parent pointers of every node (for root assume parent pointer to be null), write code to find the diameter
of tree.

---------------------------------------------------------

I had to look up what diameter of a
tree is: length of longest path between two leaves. My solution is in Java and I'm using the original data structure, without building a regular tree structure first.

The general idea is to start at the leaf nodes and traverse the tree towards the root. Each node is annotated with the maximum height and the max diameter for this node.
The diameter only gets updated once - when we hit a path that is already annotated and then we skip to the next iteration. If during traversal we hit a node that has a bigger height than our current path, skip to the next iteration.

Asymptotic Running Time:

O(n) to identify leaf nodes

O(n) to traverse tree

-> O(n)

To see that O(n) is true for the tree traversal:

We visit each leaf node once.

Each inner node is visited only once if it is only on one path.

Each inner node that is on more than one path gets visited again only if the path height is higher at that point. If they were to be visited every time (worst-case),
the runtime would be O(n log n). But we can safely assume, that on average that won't happen.

int diameter(Node[] nodes) {
    // Identify leaf nodes
    // TODO could be more efficient by marking nodes that have 
    // children as: not-leaf-node 
    ArrayList<Node> leafNodes = new ArrayList<Node>(Arrays.asList(nodes));
    for(Node n: nodes) {
        leafNodes.remove(n.parent);
    }

    // walk leafNodes up to root and set max height/diameter
    // we may have to use hashmaps to set vars to nodes instead of assuming
    // member vars inside the nodes

    int treeDiameter = 0;
    for(Node n: leafNodes) {
        int height = 1;
        boolean disableDiameterUpdate = false;

        while(n != null) {
            if(!disableDiameterUpdate && n.maxHeight > 0) {
                n.diameter = height + n.maxHeight - 1;
                if(n.diameter > treeDiameter)
                    treeDiameter = n.diameter;
                disableDiameterUpdate = true;
            }

            if(n.maxHeight >= height)
                break;

            n.maxHeight = height;
            height++;
            n = n.parent;
        }
    }

    return treeDiameter;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: