classTreeNode{ int val; TreeNode left; TreeNode right;
TreeNode(int x) { val = x; } }
publicclassleetcode104_MaximumDepthofBinaryTree{ // static int i =0; // static int j = 0; // 不能在这里定义 publicstaticintmaxDepth(TreeNode root){ if (root == null) return0; int i = maxDepth(root.left); int j = maxDepth(root.right); return Math.max(i, j) + 1; }
/** * BFS 层次遍历, 记录层数,即为深度 * * @param root 根节点 * @return 二叉树的深度 */ publicstaticintmaxDepth_BFS(TreeNode root){ if (root == null) return0; LinkedList<TreeNode> queue = new LinkedList<>(); // 队列 queue.add(root); int maxDepth = 0; while (!queue.isEmpty()) { maxDepth++;// 层数加1 // 将当前层出队列 int currSize = queue.size(); for (int i = 0; i < currSize; i++) { TreeNode node = queue.poll(); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } return maxDepth; }