本文主要是介绍L50--- 104. 二叉树的最大深度(深搜)---Java版,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.题目描述
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
2.思路
这个二叉树的结构如下:
根节点 1
左子节点 2
右子节点 3
左子节点 4
计算过程
从根节点 1 开始计算:
计算左子树的最大深度:
根节点 2:
左子树为空,深度为0。
右子树为空,深度为0。
所以节点 2 的深度为 Math.max(0, 0) + 1 = 1。
计算右子树的最大深度:
根节点 3:
计算左子树的最大深度:
根节点 4:
左子树为空,深度为0。
右子树为空,深度为0。
所以节点 4 的深度为 Math.max(0, 0) + 1 = 1。
右子树为空,深度为0。
所以节点 3 的深度为 Math.max(1, 0) + 1 = 2。
最后,根节点 1 的深度为 Math.max(1, 2) + 1 = 3。
3.代码实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int maxDepth(TreeNode root) {if(root==null){return 0;}int leftDepth=maxDepth(root.left);int rightDepth=maxDepth(root.right);return Math.max(leftDepth,rightDepth)+1;}
}
这篇关于L50--- 104. 二叉树的最大深度(深搜)---Java版的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!