美文网首页
LeetCode 111. Minimum Depth of B

LeetCode 111. Minimum Depth of B

作者: 洛丽塔的云裳 | 来源:发表于2020-04-24 22:11 被阅读0次

0. 题目

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.
Note: A leaf is a node with no children.


1. C++版本

思想:借助层次遍历,只统计既没有左子树,也没有右子树的节点的深度,从中去除最小深度。对于最小深度这种题目,就考虑用宽度优先算法,而对于最大深度,就用深度优先算法

    int minDepth(TreeNode* root) {
        queue<TreeNode*> fatherQueue, childQueue;
        int depth = 1, minDepth=0;
        bool isFirst = true;
        if (root) {
            fatherQueue.push(root);
        }
        while (!fatherQueue.empty()) {
            TreeNode* currNode = fatherQueue.front();
            fatherQueue.pop();
            if (!currNode->left && !currNode ->right) {
                if (isFirst) { 
                    minDepth = depth;
                    isFirst = false; 
                }
                else if(!isFirst && depth < minDepth) 
                    minDepth = depth;
            }
            if (currNode->left) {
                childQueue.push(currNode->left);
            }
            if (currNode->right) {
                childQueue.push(currNode->right);
            }
            if (fatherQueue.empty() && !childQueue.empty()) {
                swap(fatherQueue, childQueue);
                depth += 1;
            }
        }
        return minDepth;
    }

2. python版本

相关文章

网友评论

      本文标题:LeetCode 111. Minimum Depth of B

      本文链接:https://www.haomeiwen.com/subject/pfwbihtx.html