Consider the following C program segment
struct CellNode{ struct CellNode *leftChild int element; struct CellNode *rightChild; }; int Dosomething (struct CellNode *ptr) { int value = 0; if(ptr != NULL) { if (ptr -> leftChild != NULL) value = 1 + DoSomething (ptr -> leftChild); if (ptr -> rightChild != NULL) value = max(value, 1 + Dosomething (ptr -> rightChild)); } return(value); }
The value returned by the function $\text{DoSomething}$ when a pointer to the root of a non-empty tree is passed as argument is
1st if calculates the height of the left subtree and 2nd if computes the height of the right subtree and takes the max of (height of left subtree, height of right subtree).
Take this tree .
Result for all options will be as follows:
A- 4
B-7
C-3
D-2
Running given code we get 2 as answer . So option D is right
The below diagram may make the code easier to understand.
How I did that: I drew a tree then just tried the algo on this tree and then I modified the tree wisely, then I tried the algo one more time
what kind of explanation is this? :D :D
Try to run code on this type of tree:
1.here node at the same level are sibling(are right subtree).
It is kind of representaion of n ary tree.
Your figure can be represented as
You will get answer as D
64.3k questions
77.9k answers
244k comments
80.0k users