diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 20cf4ef2..ccecea43 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -231,19 +231,53 @@ public: Java: -```java + +```Java class Solution { + /** + * 递归法 + */ public int maxDepth(TreeNode root) { if (root == null) { return 0; } - int leftdeep = maxDepth(root.left); - int rightdeep = maxDepth(root.right); - return 1+Math.max(leftdeep,rightdeep); + 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: