2019 Dec Platinum Problem 3 Tree Depth

From Wiki
Jump to navigation Jump to search

Official Problem Statement[edit]

Tree Depth

Problem Statement:

Given a rooted tree with N nodes, find the maximum depth of the tree.

Solution:

The maximum depth of a tree can be found by traversing the tree and keeping track of the maximum depth seen so far. In C++, this can be done using a recursive function:

int maxDepth(Node* root) 
{ 
    if (root == NULL) 
        return 0; 
  
    int left_depth = maxDepth(root->left); 
    int right_depth = maxDepth(root->right); 
  
    return max(left_depth, right_depth) + 1; 
} 

The function takes the root node of the tree as an argument and returns the maximum depth of the tree. It first checks if the root is NULL, in which case the depth is 0. Otherwise, it recursively calls the function on the left and right subtrees, and returns the maximum of the two depths plus 1 (to account for the current node).