美文网首页
二叉树最大深度【递归、迭代】

二叉树最大深度【递归、迭代】

作者: 瑜小贤 | 来源:发表于2019-12-13 15:21 被阅读0次

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

方法一:递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }else{
            int leftDepth = maxDepth(root.left);
            int rightDepth = maxDepth(root.right);
            return Math.max(leftDepth, rightDepth) + 1;
        }
    }
}
复杂度分析
  • 时间复杂度:
    我们每个结点只访问一次,因此时间复杂度为 O(n), 其中 n 是结点的数量。

  • 空间复杂度:
    在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 n 次(树的高度),因此保持调用栈的存储将是 O(n)。但在最好的情况下(树是完全平衡的),树的高度将是 log (N)。因此,在这种情况下的空间复杂度将是 O(log(N))

方法二:迭代

我们还可以在栈的帮助下将上面的递归转换为迭代。

我们的想法是使用 DFS 策略访问每个结点,同时在每次访问时更新最大深度。

所以我们从包含根结点且相应深度为 1 的栈开始。然后我们继续迭代:将当前结点弹出栈并推入子结点。每一步都会更新深度。

class Solution {
  public int maxDepth(TreeNode root) {
    Queue<Pair<TreeNode, Integer>> stack = new LinkedList<>();
    if (root != null) {
      stack.add(new Pair(root, 1));
    }

    int depth = 0;
    while (!stack.isEmpty()) {
      Pair<TreeNode, Integer> current = stack.poll();
      root = current.getKey();
      int current_depth = current.getValue();
      if (root != null) {
        depth = Math.max(depth, current_depth);
        stack.add(new Pair(root.left, current_depth + 1));
        stack.add(new Pair(root.right, current_depth + 1));
      }
    }
    return depth;
  }
};
复杂度分析
  • 时间复杂度:O(n)

  • 空间复杂度:O(n)

补充知识:二叉树的 深度 和 高度 概念不同,深度是指从根节点到该节点的最长简单路径边的条数,而高度是指从该节点到叶子节点的最长简单路径边的条数。

相关文章

网友评论

      本文标题:二叉树最大深度【递归、迭代】

      本文链接:https://www.haomeiwen.com/subject/bivfnctx.html