二叉树的最小深度

二叉树的最小深度直觉上和二叉树的最大深度差不多,但其实存在一个误区,也就是根节点的左子树或者右子树不存在,如果不加判断条件,很容易将二叉树的最小深度求为1

且深度为二叉树到叶子结点的距离,而叶子结点为左右子树都为空的节点,在求深度时要判断是否为叶子结点

写递归法的代码时,要注意节点的左右子树情况:(1)左子树存在,右子树不存在,最小深度为1+左子树深度(2)右子树存在,左子树不存在,最小深度为1+右子树深度。代码如下:

class Solution {
public:
    int getDepth(TreeNode* root){
        if(root == nullptr) return 0;
        int ldepth = getDepth(root->left);
        int rdepth = getDepth(root->right);
        if(root->left != nullptr && root->right == nullptr) return 1 + ldepth;
        if(root->left == nullptr && root->right != nullptr) return 1 + rdepth;
        int depth = 1 + min(ldepth, rdepth);
        return depth;
    }
    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

写迭代法代码时,要判断节点是否为叶子节点,是叶子结点时返回深度,即为二叉树的最小深度

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值