2019 Dec Platinum Problem 3 Tree Depth

From Wiki
Revision as of 23:00, 11 June 2023 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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).