Post

lc.104 求二叉树最大(小)深度

lc.104 求二叉树最大(小)深度

![[Pasted image 20241124002835.png]]
![[Pasted image 20241124002904.png]]
在层序遍历模板的基础上加一个depth即可

求二叉树的最小深度

相对于 104.二叉树的最大深度 ,本题还也可以使用层序遍历的模板来解决,思路是一样的。

需要注意的是,只有当左右孩子都为空的时候,才说明遍历的最低点了。如果其中一个孩子为空则不是最低点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();
            depth++; // 记录最小深度
            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) { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
                    return depth;
                }
            }
        }
        return depth;
    }
};
This post is licensed under CC BY 4.0 by the author.