当前位置: 首页 > news >正文

55 - I. 二叉树的深度


comments: true
difficulty: 简单
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9855%20-%20I.%20%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%B7%B1%E5%BA%A6/README.md

面试题 55 - I. 二叉树的深度

题目描述

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

例如:

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

    3/ \9  20/  \15   7

返回它的最大深度 3 。

 

提示:

  1. 节点总数 <= 10000

注意:本题与主站 104 题相同:https://leetcode.cn/problems/maximum-depth-of-binary-tree/

解法

方法一:递归

我们可以用递归的方法来解决这道题。递归的终止条件是当前节点为空,此时深度为 0 0 0;如果当前节点不为空,则当前的深度为其左右子树深度的最大值加 1 1 1,递归计算当前节点的左右子节点的深度,然后返回它们的最大值加 1 1 1

时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n)。其中 n n n 是二叉树的节点数。最坏情况下,二叉树退化为链表,递归深度达到 n n n,系统使用 O ( n ) O(n) O(n) 大小的栈空间。

Python3
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def maxDepth(self, root: TreeNode) -> int:if root is None:return 0return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
Java
/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/
class Solution {public int maxDepth(TreeNode root) {if (root == null) {return 0;}return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));}
}
C++
/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int maxDepth(TreeNode* root) {if (!root) {return 0;}return 1 + max(maxDepth(root->left), maxDepth(root->right));}
};
Go
/*** Definition for a binary tree node.* type TreeNode struct {*     Val int*     Left *TreeNode*     Right *TreeNode* }*/
func maxDepth(root *TreeNode) int {if root == nil {return 0}l, r := maxDepth(root.Left), maxDepth(root.Right)if l > r {return 1 + l}return 1 + r
}
Rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {match root {None => 0,Some(node) => {let mut node = node.borrow_mut();let left = node.left.take();let right = node.right.take();1 + Self::max_depth(left).max(Self::max_depth(right))}}}
}
JavaScript
/*** Definition for a binary tree node.* function TreeNode(val) {*     this.val = val;*     this.left = this.right = null;* }*/
/*** @param {TreeNode} root* @return {number}*/
var maxDepth = function (root) {if (!root) {return 0;}return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
};
C#
/*** Definition for a binary tree node.* public class TreeNode {*     public int val;*     public TreeNode left;*     public TreeNode right;*     public TreeNode(int x) { val = x; }* }*/
public class Solution {public int MaxDepth(TreeNode root) {if (root == null) {return 0;}return 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right));}
}
Swift
/* public class TreeNode {
*     public var val: Int
*     public var left: TreeNode?
*     public var right: TreeNode?
*     public init(_ val: Int) {
*         self.val = val
*         self.left = nil
*         self.right = nil
*     }
* }
*/class Solution {func maxDepth(_ root: TreeNode?) -> Int {guard let root = root else {return 0}return 1 + max(maxDepth(root.left), maxDepth(root.right))}
}
http://www.lryc.cn/news/435645.html

相关文章:

  • Redis——初识Redis
  • Xshell or Xftp提示“要继续使用此程序,您必须应用最新的更新或使用新版本”
  • table用position: sticky固定多层表头,滑动滚动条border边框透明解决方法
  • 基于飞桨paddle2.6.1+cuda11.7+paddleRS开发版的目标提取-道路数据集训练和预测代码
  • 数学建模笔记—— 整数规划和0-1规划
  • [001-03-007].第26节:分布式锁迭代3->优化基于setnx命令实现的分布式锁-防锁的误删
  • 【Unity踩坑】为什么有Rigidbody的物体运行时位置会变化
  • NGINX开启HTTP3,给web应用提个速
  • 秋招季!别浮躁!
  • Java的时间复杂度和空间复杂度和常见排序
  • Qt 学习第十天:标准对话框 页面布局
  • 体育数据API纳米足球数据API:足球数据接口文档API示例⑩
  • [数据集][目标检测]高铁受电弓检测数据集VOC+YOLO格式1245张2类别
  • Vuex:深入理解所涉及的几个问题
  • vue原理分析(六)研究new Vue()
  • 滑动窗口+动态规划
  • vscode配置django环境并创建django项目
  • WebGL系列教程四(绘制彩色三角形)
  • 通过mxGraph在ARMxy边缘计算网关上实现工业物联网
  • GEE案例:利用sentinel-1数据进行洪水监测分析(直方图统计)
  • QT 联合opencv 易错点
  • 例如/举例的使用方法 ,e.g., 以及etc的使用方法
  • 20240902-VSCode-1.19.1-部署vcpkg-win10-22h2
  • MySQL学习(多表操作)
  • 鸿蒙开发(NEXT/API 12)【网络连接管理】 网络篇
  • VMware Fusion虚拟机Mac版 安装Ubuntu操作系统教程
  • 基于SpringBoot+Vue+MySQL的房屋租赁管理系统
  • 虚拟机器配置固定IP地址
  • 用python实现基于形态学的方法,如开运算和闭运算,来去除pcd格式激光点云中的植被
  • QT 绘制简易时钟