Easy reading 12ms C++ solution


  • 13
    B
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if (root==nullptr){
                return 0;
            }
            else if (root->right==nullptr||root->left==nullptr){
                return max(minDepth(root->left),minDepth(root->right))+1;
            }
            else{
                return min(minDepth(root->left),minDepth(root->right))+1;
            }
        }
    };

  • 0
    K
    class Solution {
    public:
        int minDepth(TreeNode* root) {
      		if (root == NULL)
    			return 0;
    		queue<TreeNode*> q;
    		q.push(root);
    		
    		int count = 0;
    		while (q.size())
    		{
    			count++;
    			int n = q.size();
    			for (int i = 0; i < n; i++)
    			{
    				TreeNode* node;
    				node = q.front();
    				q.pop();
    
    				if (!node->left && !node->right)
    				{
    					return count;
    				}
    
    				if (node->left)
    					q.push(node->left);
    				if (node->right)
    					q.push(node->right);
    			}
    			
    		}
    
    		return count;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.