每日一练:LeeCode-104. 二叉树的最大深度【二叉树】

本文是力扣LeeCode-104. 二叉树的最大深度 学习与理解过程,本文仅做学习之用,对本题感兴趣的小伙伴可以出门左拐LeeCode

给定一个二叉树 root ,返回其最大深度
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数

示例 1:

在这里插入图片描述

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:
输入:root = [1,null,2]
输出:2

提示:
树中节点的数量在 [0, 104] 区间内。
-100 <= Node.val <= 100

思路

做二叉树的题目,首先需要确认的是遍历顺序,这道题,可以用后序遍历:左右中,也可以用前序遍历:中左右,笔者这里采用后序遍历,因为理解和书写更适合刷题宝宝。

  • 确定递归函数的参数和返回值: int getDepth(TreeNode node)
  • 确定终⽌条件: if(node==null)return 0;
  • 确定单层递归的逻辑:
        int leftHeight = getDepth(node.left);	//左
        int rightHeight = getDepth(node.right);	//右
        int height = 1+Math.max(leftHeight,rightHeight);	//中
        return height;

代码实现

class Solution {
   
    public int maxDepth(TreeNode root) {
   
        return getDepth(root);
    }

    private int getDepth(TreeNode node){
   
        if(node==null)return 0;	//遇到叶子结点返回
        int leftHeight = getDepth(node.left);	//递归返回遍历到当前节点node的左子树的深度
        int rightHeight = getDepth(node.right);	//递归返回遍历到当前节点node的右子树的深度
        int height= 1+Math.max(leftHeight,rightHeight);	//取当前节点下最深的左子树或右子树,并+1(当前节点)
        return height;
    }
}

优化代码实现

class Solution {
   
    public int maxDepth(TreeNode root) {
   
        if(root==null)return 0;
        return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }
}

最终要的一句话:做二叉树的题目,首先需要确认的是遍历顺序

大佬们有更好的方法,请不吝赐教,谢谢

相关推荐

  1. LeetCode104 深度

    2024-01-10 10:20:02       19 阅读
  2. [leetcode] 104. 深度

    2024-01-10 10:20:02       20 阅读
  3. LeetCode104.深度

    2024-01-10 10:20:02       14 阅读
  4. Leetcode 104. 深度

    2024-01-10 10:20:02       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-10 10:20:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-10 10:20:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-10 10:20:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-10 10:20:02       20 阅读

热门阅读

  1. MATLAB对数据隔位抽取和插值的几种方法

    2024-01-10 10:20:02       35 阅读
  2. 【气候极端指数】MATLAB计算各种气候极端指数

    2024-01-10 10:20:02       39 阅读
  3. ES6---判断对象是否为{}

    2024-01-10 10:20:02       29 阅读
  4. go 的内存布局和分配原理

    2024-01-10 10:20:02       31 阅读
  5. 服务器访问慢怎么办?

    2024-01-10 10:20:02       37 阅读
  6. DataGear专业版 1.0.0 发布,数据可视化分析平台

    2024-01-10 10:20:02       38 阅读