Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
* 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 {
int minDepth(TreeNode* root) {
//if there is no node in the tree
return 0;
//if the current node do not have any child node
else if(!root->left && !root->right)
return 1;
else if(!root->left)
return minDepth(root->right)+1;
else if(!root->right)
return minDepth(root->left)+1;
//find minimum depth from left and right subtree
return min(minDepth(root->left),minDepth(root->right))+1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment