来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

描述

给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。

题解

递归法

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int maxDepth(TreeNode root) {
  12. if (null == root) {
  13. return 0;
  14. } else {
  15. int leftHeight = maxDepth(root.left);
  16. int rightHeight = maxDepth(root.right);
  17. return Math.max(leftHeight, rightHeight) + 1;
  18. }
  19. }
  20. }

复杂度分析

  • 时间复杂度:我们每个结点只访问一次,因此时间复杂度为104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图1,其中104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图2是结点的数量。
  • 空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图3次(树的高度),因此保持调用栈的存储将是104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图4。但在最好的情况下(树是完全平衡的),树的高度将是104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图5。因此,在这种情况下的空间复杂度将是104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图6

    迭代法

    类似于「二叉树的层序遍历」

    1. class Solution {
    2. public int maxDepth(TreeNode root) {
    3. if (root == null) {
    4. return 0;
    5. }
    6. Queue<TreeNode> queue = new LinkedList<>();
    7. queue.add(root);
    8. int ans = 0;
    9. while (!queue.isEmpty()) {
    10. int size = queue.size();
    11. for (int i = 0; i < size; i++) {
    12. TreeNode node = queue.poll();
    13. if (node.left != null) {
    14. queue.add(node.left);
    15. }
    16. if (node.right != null) {
    17. queue.add(node.right);
    18. }
    19. }
    20. ans++;
    21. }
    22. return ans;
    23. }
    24. }

    复杂度分析

  • 时间复杂度:104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图7,其中n为二叉树的节点个数。与方法一同样的分析,每个节点只会被访问一次。

  • 空间复杂度:此方法空间的消耗取决于队列存储的元素数量,其在最坏情况下会达到104. 二叉树的最大深度(Maximum Depth of Binary Tree) - 图8