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.
算法1:dfs递归的求解
1 class Solution { 2 public: 3 int minDepth(TreeNode *root) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 if(root == NULL)return 0; 7 int res = INT_MAX; 8 dfs(root, 1, res); 9 return res; 10 } 11 void dfs(TreeNode *root, int depth, int &res) 12 { 13 if(root->left == NULL && root->right == NULL && res > depth) 14 {res = depth; return;} 15 if(root->left) 16 dfs(root->left, depth+1, res); 17 if(root->right) 18 dfs(root->right, depth+1, res); 19 } 20 };