leetcode : Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

简单题思路略过,一种bfs时如果需要分层处理的好办法是使用两个容器交替保存第n层与n+1层。虽然该题可以用个int保存每一层的节点数,但是做法很别扭而且空间复杂度的数量级并不会减少

 

AC代码:

class Solution {
public:
    int minDepth(TreeNode *root) {
        if(!root)
            return 0;
        vector<TreeNode *> q[2];
        q[0].push_back(root);
        int current = 1,next = 0;
        int minDep = 0;
        while(1){
            current = !current;
            next = !next;
            ++minDep;
            for(auto w : q[current]){
                if(!w->left && !w->right)
                    return minDep;
                if(w->left)
                    q[next].push_back(w->left);
                if(w->right)
                    q[next].push_back(w->right);
            }
            q[current].clear();
        }
        
    }
};

 

posted on 2014-11-20 14:27  远近闻名的学渣  阅读(135)  评论(0)    收藏  举报

导航