Iterative and recursive solutions in cpp, best-submission


  • 0
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if(!root) return 0;
            vector<TreeNode*> queue0, queue1;
            int level = 0;
            queue0.push_back(root);
            while(queue0.size())
            {
                level++;
                for(auto& t: queue0)
                {
                    if(!t->left && !t->right) return level;
                    if(t->left) queue1.push_back(t->left);
                    if(t->right) queue1.push_back(t->right);
                }
                queue0.swap(queue1);
                queue1.clear();
            }
            return level; 
        }
    };
    

    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if(!root) return 0;
            if(!root->left && !root->right) return 1;
            if(root->left && root->right)
            return min(minDepth(root->left), minDepth(root->right))+1;
            if(root->left) return minDepth(root->left)+1;
            if(root->right) return minDepth(root->right)+1;
            return 0;
        }
    };

Log in to reply
 

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