Accepted iterative C++ code, 14ms


  • 0
    K
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if (root == NULL) return 0;
            stack<TreeNode*> sta;
            vector<int> depths;
            TreeNode* tmp;
            root->val = 1;
            sta.push(root);
            while (!sta.empty()){
                tmp = sta.top();
                sta.pop();
                if (tmp->left==NULL && tmp->right==NULL){
                    depths.push_back(tmp->val);
                }else{
                    if (tmp->left){
                        tmp->left->val = tmp->val + 1;
                        sta.push(tmp->left);
                    }
                    if (tmp->right){
                        tmp->right->val = tmp->val + 1;
                        sta.push(tmp->right);
                    }
                }
            }
            return *std::min_element(depths.begin(),depths.end());
        }
    };

Log in to reply
 

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