The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in the pseudo-code below is invoked as height (root) to compute the height of a binary tree rooted at the tree pointer root.
The appropriate expressions for the two boxes B1 and B2 are:
In tree many variation of question can be asked like count no of internal nodes,no of leaf nodes,no of nodes which has only left child or right child , no of nodes with degree 2 and many more.
So next question how can we answer such problems??
so generally code will be given to us and they would left some blank space and out of given option we have to fill the blank space .
the best approach i can find as of now for verifying option is Stack method . In Tree generally node would be called preorder and execution will done postorder. So start running the code by pushing root (by taking a simple example)in stack it and and also keep in mind where you have gone to call next node (line no) continue this push and pop operation until you get the asked value.
if any one is having any other approaches then ...please share
Answer is option A.
From the diagram below we are able to see how this works :
I got a hint ; How to quickly approach this type of question :--In this type of questions where we already know we want to find something(i.e. Height ) then simply draw min possible tree which reach us upto the Given Boxes.
For Box1,Box2 tree will be as given in below img :-->
Now Analyse the code for above trees we get Option A as Ans.
1st if condition is true only if there is no node in binary tree.
2nd if condition told if there is only 1 node in the tree.Then height of tree is 0.
if the tree has at least one left node, then it is going to calculate B2
otherwise, if the tree has only right subtree, tree height calculated by B1 only
B1= right subtree+1 to get height of the tree
Now, h1= height of right subtree of a node
h2= height of left subtree of a node
height of a tree= 1+ max(h1,h2)
h1 is height of left subtree and h2 height of right subtree.
Now, to get total height of tree we have to add root with max (left subtree, right subtree) of the tree.