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 if(root == NULL) 14 return 0; 15 if(root->left == NULL && root->right == NULL) 16 return 1; 17 if(root->left == NULL && root->right != NULL) 18 return minDepth(root->right) + 1; 19 if(root->left != NULL && root->right == NULL) 20 return minDepth(root->left) + 1; 21 else 22 return min(minDepth(root->left), minDepth(root->right)) + 1; 23 // if(root == NULL) 24 // return 0; 25 // int l = minDepth(root->left); 26 // int r = minDepth(root->right); 27 // if(l == 0) 28 // return r + 1; 29 // if(r == 0) 30 // return l + 1; 31 // return (l < r ? l : r) + 1; 32 } 33 };
bfs:
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 if(root == NULL) 14 return 0; 15 int num = 0; 16 queue<TreeNode*> q; 17 TreeNode* temp; 18 q.push(root); 19 while(!q.empty()){ 20 num++; 21 int len = q.size(); 22 while(len--){ 23 temp = q.front(); 24 q.pop(); 25 if(temp->left == NULL && temp->right == NULL) 26 return num; 27 if(temp->left != NULL) 28 q.push(temp->left); 29 if(temp->right != NULL) 30 q.push(temp->right); 31 } 32 } 33 } 34 };