Saturday, September 20, 2014

LeetCode: 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 binary tree  
  * struct TreeNode {  
  *   int val;  
  *   TreeNode *left;  
  *   TreeNode *right;  
  *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
  * };  
  */  
   #define INT_MAX 0x7FFFFFFF


   int minDepth(TreeNode *root) {  
     if(root == NULL)return 0;  
     if(!root->left && !root->right)return 1;  
     int x = minDepth(root->left);  
     int y = minDepth(root->right);  
     if(!x)x = INT_MAX;  
     if(!y)y = INT_MAX;  
     return (min(x, y) +1);  
   }  

No comments:

Post a Comment