Friday, 22 July 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.

 /**  
  * 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

Blog Archive