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 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int minDepth(TreeNode* root) { 13 //深搜递归 14 15 if(root==NULL) return 0; 16 if(!root->left&&!root->right) 17 return 1; 18 int leftdepth=minDepth(root->left); 19 int rightdepth=minDepth(root->right); 20 if(leftdepth==0) 21 return rightdepth+1; 22 else if(rightdepth==0) 23 return leftdepth+1; 24 else 25 return min(leftdepth,rightdepth)+1; 26 } 27 };