CareerCup Find the diameter of the tree

86 篇文章 0 订阅
13 篇文章 0 订阅

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值