Day16:代码随想录训练营第16天 | 104.二叉树的最大深度

104.二叉树的最大深度

题目链接:104. 二叉树的最大深度 - 力扣(LeetCode) 

题解:

本题使用递归法,使用后序遍历求树的高度,依旧是递归三部曲。

1.确定参数和返回值

int getdepth(TreeNode* node)

 2.确定终止条件:如果空节点,那么返回0,表示高度也为0

if (node == NULL) return 0;

3.确定单层递归的逻辑:先求左子树,再求右子树的深度,最后取左右深度最大值+1(因为+1是把中间节点也算进去)就是节点位根节点的树的深度。

int leftdepth = getdepth(node->left);
int rightdepth = getdepth(node->right);
int depth = 1 + max(leftdepth,rightdepth);
return depth;

 总结C++代码:

class solution {
public:
    int getdepth(TreeNode* node) {
        if (node == NULL) return 0;
        int leftdepth = getdepth(node->left);       // 左
        int rightdepth = getdepth(node->right);     // 右
        int depth = 1 + max(leftdepth, rightdepth); // 中
        return depth;
    }
    int maxDepth(TreeNode* root) {
        return getdepth(root);
    }
};

111.二叉树的最小深度

题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)

题解: 

 首先最小深度是从根节点到最近叶子节点的最短路径上的节点数量。叶子节点:左右孩子都为空的节点才是叶子节点!依旧是递归三部曲。

1.确定递归函数的参数和返回值

int getDepth(TreeNode* node)

 2.确定终止条件

if (node == NULL) return 0;

3.确定单层递归的逻辑(注意:这里有个坑,正确逻辑理解为如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。)

int leftDepth = getDepth(node->left);           // 左
int rightDepth = getDepth(node->right);         // 右
                                                // 中
// 当一个左子树为空,右不为空,这时并不是最低点
if (node->left == NULL && node->right != NULL) { 
    return 1 + rightDepth;
}   
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) { 
    return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;

总结C++代码:

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值