Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the total depth of every node in a binary search tree recursively?

I have been at this problem for awhile now and I can't quite figure the logic. Say I have a binary tree that looks something like the following:

        8                    1 * 0 =  0
      /   \
     4    12                 2 * 1 =  2
    / \   / \
   2   6 10 14               4 * 2 =  8
                                    ----
                                     10

I want to find the depth of each node and add those numbers all together to get a total. The code I've got right now looks something like this:

private int totalDepth(Node node, int depth) 
{
    if(node == null) 
    {
        return 0;
    }

    return totalDepth(node.left, depth + 1) + totalDepth(node.right, depth + 1);
}

I figured this would recursively add one to each level deeper for the left side of the the tree (8 -> 4 -> 2) before traversing the right side, but it doesn't quite work.

I've tweaked this method any number of ways but can't seem to nail down what I'm missing. Any help would be GREATLY appreciated.

like image 544
Andrew Avatar asked Oct 20 '12 03:10

Andrew


People also ask

How do you find the depth of all nodes in a binary tree?

Approach: The problem can be solved based on the following observations: Depth of a node K (of a Binary Tree) = Number of edges in the path connecting the root to the node K = Number of ancestors of K (excluding K itself).

How do you find the number of nodes in a binary search tree recursively?

Find the left and the right height of the given Tree for the current root value and if it is equal then return the value of (2height – 1) as the resultant count of nodes. Otherwise, recursively call for the function for the left and right sub-trees and return the sum of them + 1 as the resultant count of nodes.

What is the expected depth of a node in a binary search tree?

Theorem. The average depth of a node in a randomly constructed binary search tree is O(log n). D(i)+(n − 1).

How do you find the height of a binary tree recursively?

To calculate the height of the tree recursively, we need to find the height of it's left subtree and right subtree recursively and add 1 to them (height between the topmost node and its children).


1 Answers

You are almost there: you have added up the results for the left and the right subtree, but you have forgotten to add the result for the node itself:

return depth                              // myself
     + totalDepth(node.left, depth + 1)   // my left subtree
     + totalDepth(node.right, depth + 1); // my right subtree
like image 196
Sergey Kalinichenko Avatar answered Nov 01 '22 14:11

Sergey Kalinichenko