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 a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if (root==nullptr) return 0; queue<TreeNode*> q; q.push(root); int depth = 1; while(!q.empty()) { int sz = q.size(); for(int i = 0; i < sz;i++) { TreeNode* cur = q.front(); q.pop(); if (cur->left == nullptr && cur->right == nullptr) { return depth; } if (cur->left != nullptr) q.push(cur->left); if (cur->right!= nullptr) q.push(cur->right); } depth++; } return depth; } };
1 class Solution { 2 public: 3 4 int minDepth(TreeNode* root) { 5 if (root == nullptr) return 0; 6 if (root->left != nullptr && root->right != nullptr) { 7 return 1 + min(minDepth(root->left),minDepth(root->right)); 8 } else if (root->left != nullptr && root->right == nullptr) { 9 return 1 + minDepth(root->left); 10 } else if (root->left == nullptr && root->right != nullptr) { 11 return 1 + minDepth(root->right); 12 } 13 return 1; 14 } 15 };