Sunday 13 August 2017

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Height of empty binary tree is 0 and with just root node is 1.
                                    1
                                 /     \
                                2       3
                                 \
                                  5
For the above example, the maximum depth is 3 following the path 1-2-5.

Approach : Using the recursive approach as implemented below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int max(int a, int b){
    return a >= b ? a : b;
}
int maxDepth(struct TreeNode* root) {
    int height;
    //base case
    if(root == NULL){
        return 0;
    }
    //recursively compute left and right height and return the maximum
    height = 1 + max(maxDepth(root->left), maxDepth(root->right));
    return height;
}
Share:

0 comments:

Post a Comment