leetcode之二叉树三: 二叉树的最大深度
2021/5/5 10:56:04
本文主要是介绍leetcode之二叉树三: 二叉树的最大深度,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
原题: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/submissions/
一、题目要求
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
二、解题
package com.leetcode.test.tree; /** * 二叉树的最大深度 */ public class Solution3 { public static void main(String[] args) { TreeNode a1 = new TreeNode(3); TreeNode a2 = new TreeNode(9); TreeNode a3 = new TreeNode(20); TreeNode a4 = new TreeNode(15); TreeNode a5 = new TreeNode(7); a1.left = a2; a1.right = a3; a3.left = a4; a3.right = a5; System.out.println(maxDepth(a1)); } //二叉树的最大深度等于 1+ max(左子树的最大深度, 右子树的最大深度) public static int maxDepth(TreeNode root) { if (root == null){ return 0; } return 1 + Math.max(maxDepth(root.left),maxDepth(root.right)); } }
三、运行结果
四、提交结果
这篇关于leetcode之二叉树三: 二叉树的最大深度的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享