int BST::depthHelper(Node *node){ if(node == NULL){ return 0; } else return 1+max(depthHelper(node->left),depthHelper(node->right)); }
int BST::diameterHelper(Node *node){ if(node == NULL){ return 0; } else{ int lheight = depthHelper(node->left); int rheight = depthHelper(node->right); int ldiameter = diameterHelper(node->left); int rdiameter = diameterHelper(node->right); return max(max(1+lheight+rheight,ldiameter),rdiameter); } }
size_t Tree<NODETYPE>::depthHelper(TreeNode<NODETYPE> *ptr) const { // base case if (ptr == 0) { return 0; } else { size_t ldepth = depthHelper(ptr->leftPtr); size_t rdepth = depthHelper(ptr->rightPtr); if (ldepth <= rdepth) { return rdepth + 1; } else { return ldepth + 1; } } }
//========================depthHelper================================= // A helper method that recursively calcuates the depth of the // provided Object. // // Preconditions: The Object is not NULL. // // Postconditions: Returns the depth of the given Object. If the // Returns -1 the Object is not found. //==================================================================== int BSTree::depthHelper (Node *root, const Object &the_item) const { // Item not found. if (root == NULL) return -1; // Found it. if (*root->item == the_item) return 0; int subtree = depthHelper (root->left, the_item); if (subtree == -1) subtree = depthHelper (root->right, the_item); if (subtree == -1) return -1; else return 1 + subtree; }
//Find the maximum depth of BST int BST::depth(){ if(root == NULL){ cout<<endl<<"BST with no elements"<<endl; return 0; } else return depthHelper(root); }
//========================depth======================================= // Returns the depth of a character in the tree. The depth // of root is 0. // // Preconditions: my_root is not NULL. // // Postconditions: Returns the depth of the character in this tree, // returns -1 if not found. //==================================================================== int BSTree::depth (const Object &the_item) const { return depthHelper(my_root, the_item); }