Saturday, 13 August 2016

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == NULL)
            return 0;
        //if it is a leaf node
        if(root->left == NULL && root->right == NULL)
            return 1;
            
        int leftDepth, rightDepth;

        //if left is not NULL, recursively compute the depth of left else it is a internal node and it can't give the minDepth
        if(root ->left != NULL)
            leftDepth = minDepth(root->left);
        else
            leftDepth = INT_MAX;

        //if right is not NULL, recursively compute the depth of right tree else it is a internal node and it can't give the minDepth
        if(root ->right != NULL)
            rightDepth = minDepth(root->right);
        else
            rightDepth = INT_MAX;
        
        return 1 + min(leftDepth, rightDepth);
    }
};
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts