1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33


int minDepth(TreeNode *root) {
    if (root == NULL) return 0;

    queue<TreeNode*> nQueue; //queue for level order traversal
    queue<int> dQueue; //queue for depth associated with node

    nQueue.push(root);
    dQueue.push(1);

    while(!nQueue.empty()) {
        TreeNode *n = nQueue.front();
        int depth = dQueue.front();

        nQueue.pop();
        dQueue.pop();

        if (n->left == NULL 
            && n->right == NULL) 
            return depth;

        ++depth;
        if (n->left != NULL) {
            nQueue.push(n->left);
            dQueue.push(depth);
        }

        if (n->right != NULL) {
            nQueue.push(n->right);
            dQueue.push(depth);
        }
    }
}
View Program Text


Test Status