厦门网站建设680,wordpress 被墙,江苏国家住房和城乡建设部网站,长沙网站搭建首选智投未来题目描述#xff1a;给定一个二叉树 #xff0c;返回其最大深度。root 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 获得更多#xff1f;算法思路:代码文档#xff0c;算法解析的私得。 运行效果 完整代码 /*** 2 * Author: LJJ* 3 * Date: 2023/… 题目描述给定一个二叉树 返回其最大深度。root 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 获得更多算法思路:代码文档算法解析的私得。 运行效果 完整代码 /*** 2 * Author: LJJ* 3 * Date: 2023/8/15 9:04* 4*/public class MaxDepthBinaryTree {static class TreeNode{int val ;TreeNode left;TreeNode right;TreeNode(int val){this.val val;}}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;}public static void main(String[] args){MaxDepthBinaryTree maxDepthBinaryTree new MaxDepthBinaryTree();// 构造二叉树TreeNode root new TreeNode(3);root.left new TreeNode(9);root.right new TreeNode(20);root.right.left new TreeNode(15);root.right.right new TreeNode(7);// 计算最大深度int maxDepth maxDepthBinaryTree.maxDepth(root);System.out.println(二叉树的最大深度为 maxDepth); // 输出最大深度}
}