Delivered by FeedBurner

New Answers in your Inbox

CS-62 JUNE 2003 QNO 1(c)

Question: Write a function that takes only a pointer to the root of a binary tree T and computes the number of nodes in T.

Answer: When we traverse a binary tree then all the nodes of tree should traversed. Now if we put a pointer as a counter than it will print the total no of nodes. Any of the traversal schemes can be used to determine the number of elements in abinery tree. But we can use this mechanism also to count the total no. of neds of left subtree and right subtree.
The function is as follows:
int TotalNodes(bnodes*tree)
{
if(tree==(bnode*true)NULL)
return 0;
else
return (TotalNodes(tree->left)+TotalNodes(tree->right)+1);
}

No comments: