Diamter of tree

as we calculate the diameter by postorder traversal can we do it by inorder traversal??

Pair left = fastDiameter(root->left);
p.height = max(left.height,right.height) + 1;
p.diameter = max(left.height+right.height, max(left.diameter,right.diameter));
Pair right = fastDiameter(root->right);

the code for inorder computation would look something like this error ajayega
humesha even when we find height of tree we use post order
so in order to write fewer lines of code and avoid garbage values use postorder

But mam why cannot we use in order and how to decide which one we should use … For any work how to decide efficiently that i want that traversal…

is that the way i showed u that there would be garbage value and since we need to access both the nodes left and right for height as well as diameter of left and right so post order is the only alternative that seems suitable

how to decide on traversal is :
…Pre-order traversal while duplicating nodes and values can make a complete duplicate of a binary tree. It can also be used to make a prefix expression (Polish notation) from expression trees: traverse the expression tree pre-orderly.
…In-order traversal is very commonly used on binary search trees because it returns values from the underlying set in order, according to the comparator that set up the binary search tree (hence the name).
…Post-order traversal while deleting or freeing nodes and values can delete or free an entire binary tree. It can also generate a postfix representation of a binary tree.
It boils down to the logistical needs of an algorithm. For example, if you don’t use post-order traversal during deletion, then you lose the references you need for deleting the child trees.

1 Like

Mam the term you are using very technicall can you simply summarise it??

please go through this article if u still dont understand then i`ll help u out

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.