@Ponnusamy K: Good question. If you don’t know the depth, you can easily calculate it. Again you can use the very commonly available depth calculation logic by iterating over the tree. If you feel it is costly, you can pre-calculate and store the depth.
Once the depth is known, you can write a simple method to return the hash as shown in the example. Hope that helps!
Thanks for stopping by!