开发者

Height of tree using depth

开发者 https://www.devze.com 2023-02-26 15:58 出处:网络
Hi All I need some direction 开发者_开发问答with respect to calculating time complexity of a function height that uses function depth to get height of a tree.

Hi All I need some direction 开发者_开发问答with respect to calculating time complexity of a function height that uses function depth to get height of a tree.

So the function is like this:

height(Tree)
height h = 0;
for(each external node of T)
 h = max(height, getdepth(external node));

The worst case of this algorithm would be when, each node is at the same level ? In this case, we end up doing the same thing for all external nodes since all nodes are going to have the same height - n*(n-some_i) = n^2 ? But thinking about it this way - when the tree is unbalanced either to the left or right, the complexity will be something will again be 1+2+3+4...+n = n^2 ?

I am a bit confused. Is this the right way of thinking about this ?

Thanks


You'd be better off starting at the root and doing a recursive traversal of the tree, keeping track of the current depth and the maximum depth seen as you go. That way you only have to traverse the tree once. If you compute the depth of each node individually, you end up traversing the tree N times, where N is the number of external nodes.

0

精彩评论

暂无评论...
验证码 换一张
取 消