APL(NARS), 3937 chars
{a←⍳⍨⍵⋄{2≥⍵:⍵-1⋄1+∇¯1+a[⍵]+a[⍵]=1}¨⍳≢⍵¨⍳≢a←⍳⍨⍵} The input has to be one array of integers (not a scalar, a vector). I have not much familiarity with this subject. It all start from one function like d below
r←d w;l;i;k;a i←1⋄l←≢w⋄p←0⋄r←⍬⋄a←⍳⍨w →0×⍳i>l⋄→3×⍳i≤2⋄→3×⍳i=k←a[i]⋄p←r[k+k=1] r,←p⋄(i p)+←1⋄→2 //14+23+40+17=94
this function d it seems fits the data test... It would work that increment one counter p that represent deep that start from 0, but if the number has index >2 and in the array of input is already calculated the deep, than assign to p the deep already calculated and continue as above. For root the deep is 0, for all the node has parent root the deep is 1. The recursive function is just the traslation of that d function from iterative to recursive, i think will be more slow because it has to recaulculate values. The complexity of the function d is the same of the function {⍳⍨⍵} i think is len(input)^2 ({⍳⍨⍵} would return the first index where appear the value in the input array), for the recursive function i don't know complexity.
Test:
f←{a←⍳⍨⍵⋄{2≥⍵:⍵-1⋄1+∇¯1+a[⍵]+a[⍵]=1}¨⍳≢⍵¨⍳≢a←⍳⍨⍵} f 0 ┌1──┐ │ ¯1│ └~──┘ f ,0 ┌1─┐ │ 0│ └~─┘ f 0 0 ┌2───┐ │ 0 1│ └~───┘ f 0 0 1 2 3 4 1 6 ┌8───────────────┐ │ 0 1 2 3 4 5 2 3│ └~───────────────┘ f 0 0 1 2 3 3 0 6 6 6 9 ┌11────────────────────┐ │ 0 1 2 3 4 4 1 2 2 2 3│ └~─────────────────────┘ f 0 0 1 1 3 0 0 6 0 8 8 10 10 8 ┌14──────────────────────────┐ │ 0 1 2 2 3 1 1 2 1 2 2 3 3 2│ └~───────────────────────────┘ f 0 0 1 1 3 0 0 6 0 8 8 10 10 3 ┌14──────────────────────────┐ │ 0 1 2 2 3 1 1 2 1 2 2 3 3 3│ └~───────────────────────────┘ It is possible to golf the d function for have
r←d w;l;i;a i←1⋄l←≢w⋄r←,0⋄a←⍳⍨w →0×⍳l<i+←1⋄r,←1+r[¯1+a[i]+a[i]=1]⋄→2 //12+20+37=69