From 4ae4ce2bcfce05e4b91f24322bbdcdcb1d9c9e2e Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:15:06 +0800 Subject: [PATCH] =?UTF-8?q?Update=200104.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0104.二叉树的最大深度 Java版本 --- problems/0104.二叉树的最大深度.md | 44 +++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 814beb55..0d3cd693 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -231,7 +231,51 @@ public: Java: +```Java +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; + } +} +``` +```Java +class Solution { + /** + * 迭代法,使用层序遍历 + */ + public int maxDepth(TreeNode root) { + if(root == null) { + return 0; + } + Deque deque = new LinkedList<>(); + deque.offer(root); + int depth = 0; + while (!deque.isEmpty()) { + int size = deque.size(); + depth++; + for (int i = 0; i < size; i++) { + TreeNode poll = deque.poll(); + if (poll.left != null) { + deque.offer(poll.left); + } + if (poll.right != null) { + deque.offer(poll.right); + } + } + } + return depth; + } +} +``` Python: