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.
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).
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.
Theorem. The average depth of a node in a randomly constructed binary search tree is O(log n). D(i)+(n − 1).
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With