题解 | #牛群排列的最大深度# java
牛群排列的最大深度
https://www.nowcoder.com/practice/b3c6383859a142e9a10ab740d8baed88
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ // write code here private int ans = 0; /** * 获取二叉树的最大深度 * * @param root TreeNode类型,表示二叉树的根节点 * @return int整型,表示二叉树的最大深度 */ public int maxDepth(TreeNode root) { // 使用深度优先搜索(DFS)来计算二叉树的最大深度 int cnt = 1; dfs(root, cnt); return ans; } /** * 深度优先搜索(DFS) * * @param root TreeNode类型,表示当前节点 * @param cnt int类型,表示当前深度 */ private void dfs(TreeNode root, int cnt) { if (root == null) { return; } if (root.left == null && root.right == null) { ans = Math.max(cnt, ans); } dfs(root.left, cnt + 1); dfs(root.right, cnt + 1); } }
代码使用的编程语言是Java。
该题考察的知识点是二叉树和深度优先搜索(DFS)。
代码的文字解释如下:
- 首先,定义了一个公共类
Solution
,其中包含一个公共方法maxDepth
。 maxDepth
方法接收一个树的根节点root
作为参数,并返回二叉树的最大深度。- 在方法中,我们定义了一个私有变量
ans
,用于保存最大深度的结果。 - 使用深度优先搜索(DFS)来计算二叉树的最大深度。
- 定义了一个私有方法
dfs
,用于进行深度优先搜索。 - 在
dfs
方法中,首先判断当前节点是否为空,如果为空则直接返回。 - 如果当前节点是叶子节点(即没有左子节点和右子节点),比较当前深度
cnt
和ans
的值,将较大的值更新给ans
。 - 然后,递归调用
dfs
方法处理左子树和右子树。 - 在递归调用前,将深度
cnt
加1传递给下一层递归。 - 最后,将最终的
ans
作为结果返回。