酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

探秘深渊之树:Java代码求解二叉树最大深度!

```java import java.util.Scanner; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; this.left = null; this.right = null; } } public class BinaryTreeDepth { public static 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; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); String[] values = input.split(" "); TreeNode root = buildTree(values, 0); int depth = maxDepth(root); System.out.println(depth); } public static TreeNode buildTree(String[] values, int index) { if (index >= values.length || values[index].equals("null")) { return null; } TreeNode root = new TreeNode(Integer.parseInt(values[index])); root.left = buildTree(values, 2 * index + 1); root.right = buildTree(values, 2 * index + 2); return root; } } ``` ######[AI写代码神器 | 309点数解答 | 2024-11-17 15:23:13]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]