leetcode 111 Minimum Depth of Binary Tree

求二叉树最小深度。

递归非常简单,见最大深度。

这里用BFS。

int minDepth(TreeNode* root) {
    if (root == NULL) return 0;
    deque<TreeNode*> q;
    int now = 1;
    int depth = 0;
    q.push_back(root);
    
    while (!q.empty()) {
        int size = now;
        now = 0;
        for (int i = 0; i < size; ++i) {
            TreeNode* n = q.front();
            q.pop_front();
            if (n->left == NULL && n->right == NULL)
                return ++depth;
            if (n->left) {
                q.push_back(n->left);
                now++;
            }
            if (n->right) {
                q.push_back(n->right);
                now++;
            }
        }
        depth++;
    }
}

 

posted on 2018-01-24 14:26  willaty  阅读(101)  评论(0编辑  收藏  举报

导航