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 binary tree 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 curMin; 13 int minDepth(TreeNode *root) { 14 // Start typing your C/C++ solution below 15 // DO NOT write int main() function 16 curMin = 9999999; 17 if(root==NULL) 18 curMin = -1; 19 DepthFirst(root,0); 20 return curMin+1; 21 } 22 void DepthFirst(TreeNode * root,int depth) 23 { 24 if(depth >= curMin) 25 return; 26 if(root == NULL) 27 return; 28 if(root->left == NULL && root->right == NULL) 29 { 30 if(curMin > depth) 31 curMin = depth; 32 return; 33 } 34 DepthFirst(root->left,depth + 1); 35 DepthFirst(root->right,depth + 1); 36 } 37 };

浙公网安备 33010602011771号