每日一练(27):二叉树的深度


title: 每日一练(27):二叉树的深度

categories:[剑指offer]

tags:[每日一练]

date: 2022/02/26


每日一练(27):二叉树的深度

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

提示:

节点总数 <= 10000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof

方法一:递归

后续遍历:

按照递归三部曲,来看看如何来写。

1.确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
代码如下:

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;
//1简化前
int getDepth(TreeNode *root) {
    if (root == 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);
}
//2简化后
int maxDepth(TreeNode* root) {
    return (root == NULL) ? 0 : 1 + max(maxDepth(root->left), maxDepth(root->right));
}

方法二:迭代法(BFS)

使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合

int maxDepth(TreeNode* root) {
	if (root == NULL) {
        return 0;
    }
    int depth = 0;
    queue<TreeNode*> que;
    que.push(root);
    while (!que.empty()) {
        depth++;
        int size = que.size();
        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);
            }
        }
    }
    return depth;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加班猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值