题目地址(104. 二叉树的最大深度)

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

题目描述

  1. 给定一个二叉树,找出其最大深度。
  2. 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
  3. 说明: 叶子节点是指没有子节点的节点。
  4. 示例:
  5. 给定二叉树 [3,9,20,null,null,15,7],
  6. 3
  7. / \
  8. 9 20
  9. / \
  10. 15 7
  11. 返回它的最大深度 3

前置知识


公司

  • 暂无

思路

image.png

关键点


代码

  • 语言支持:Java

Java Code:

递归法

  1. class Solution {
  2. public int maxDepth(TreeNode root) {
  3. if (root == null) {
  4. return 0;
  5. }
  6. int left = maxDepth(root.left);
  7. int right = maxDepth(root.right);
  8. return Math.max(left, right)+1;
  9. }
  10. }

迭代法

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public int maxDepth(TreeNode root) {
  18. Queue<TreeNode> queue = new LinkedList<>();
  19. int num = 0;
  20. if (root == null) {
  21. return num;
  22. }
  23. queue.offer(root);
  24. while (!queue.isEmpty()) {
  25. int size = queue.size();
  26. while (size>0) {
  27. TreeNode poll = queue.poll();
  28. if (poll.left != null) {
  29. queue.offer(poll.left);
  30. }
  31. if (poll.right != null) {
  32. queue.offer(poll.right);
  33. }
  34. size--;
  35. }
  36. num++;
  37. }
  38. return num;
  39. }
  40. }

复杂度分析

令 n 为数组长度。

  • 时间复杂度:104. 二叉树的最大深度 - 图2#card=math&code=O%28n%29&id=gbpB9)
  • 空间复杂度:104. 二叉树的最大深度 - 图3#card=math&code=O%28n%29&id=PKSWG)