Thursday, September 8, 2011

Find depth of a k-ary tree given a parent array : Solution 3

The problem statement is mentioned here. The first solution is here. The second solution is here.

While traversing up the tree from a leaf node, we can avoid the whole path till root if we can utilize the depth already found for nodes that were traversed earlier. This will reduce the problem to as below with extra space of .
Let DEPTH be an array of length N
Initialize all elements of DEPTH to -1
FINDDEPTH(i)
    if DEPTH[i] == -1
        if P[i] == -1
            DEPTH[i] = 0
        else
            pDepth = FINDDEPTH(P[i])

           DEPTH[i] = pDepth + 1
    return DEPTH[i]


Let L be an array of length N
Initialize all elements of L to true
for each node i from 0 to N-1
   if P[i] is not -1
       set L[P[i]] to false
   end if
end for
initialize maxDepth to 0
for each node i from 0 to N-1
    if L[i] is false, continue next node
    depth = FINDDEPTH(i)
    if maxDepth < depth
       set maxDepth = depth
    end if
end for
As can be seen, the time complexity of the algorithm is where is the number of nodes. The space complexity is . Thanks to my colleague Jignesh Parsana to help point to this solution.

No comments:

Post a Comment