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: