C++ BFS 12ms solution


  • 0
    X
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    
    struct TreeNodeWithLevel{
        TreeNode * pointer;
        int level;
        TreeNodeWithLevel(TreeNode * _pointer=NULL, int _level=0) : pointer(_pointer), level(_level) {
        }
    };
    
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if(NULL == root) return 0;
            queue<TreeNodeWithLevel> q;
            q.push(TreeNodeWithLevel(root, 1));
            int minLevel=INT_MAX;
            while(!q.empty()) {
                TreeNodeWithLevel tmp=q.front(); 
                q.pop();
                if(tmp.pointer->left == NULL && tmp.pointer->right == NULL) {
                    minLevel=min(tmp.level, minLevel); continue;
                }
                if(tmp.pointer->left != NULL)
                    q.push(TreeNodeWithLevel(tmp.pointer->left, tmp.level+1));
                if(tmp.pointer->right != NULL)
                    q.push(TreeNodeWithLevel(tmp.pointer->right, tmp.level+1));
            }
            return minLevel;
        }
    };

Log in to reply
 

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