Files
leetcode-master/problems/0111.二叉树的最小深度.md
youngyangyang04 e0b3bb9419 Update
2020-07-30 16:27:19 +08:00

1.8 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

思路

C++代码

递归

class Solution {
public:
    int process(TreeNode* node) {
        if (node == NULL) return 0;
        if (node->left == NULL && node->right != NULL) { // 当一个左右其中一个孩子为空的时候并不是最低点
            return 1 + process(node->right);
        }
        if (node->left != NULL && node->right == NULL) { // 当一个左右其中一个孩子为空的时候并不是最低点
            return 1 + process(node->left);
        }
        return 1 + min(process(node->left), process(node->right));
    }

    int minDepth(TreeNode* root) {
        return process(root);
    }
};

BFS

class Solution {
public:

    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size(); // 必须要这么写要固定size大小
            depth++;
            int flag = 0;
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                if (!node->left && !node->right) { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) break;
        }
        return depth;
    }
};

更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。