Write a recursive function to compute the depth of a binary tree. Use the defini
ID: 3574715 • Letter: W
Question
Write a recursive function to compute the depth of a binary tree. Use the definition of depth given in the textbook: the root of a (non-empty) tree is at depth 0; the children of the root are at depth 1; the children of a node at depth d are at depth d+1; an empty tree has depth -1; the depth of a non-empty tree is the maximum depth of any node in the tree. The prototype and the precondition/postcondition contract for the function have been written for you. template int depth(binary_tree_node* root_ptr);//Precondition: root_ptr is a pointer to the root of a binary tree.//The tree may be empty or non-empty.//Postcondition: The depth of the binary tree is returned.Explanation / Answer
template <class Item>
int depth(binary_tree_node<Item>* root_ptr){
if(root_ptr == NULL){
return -1;
}
else{
int ld = depth(root_ptr->left);
int rd = depth(root_ptr->right);
int max = ld > rd ? ld : rd;
return max + 1;
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.