LeetCode每日一题 104. 二叉树的最大深度

104. 二叉树的最大深度

Tag Tree DFS

Difficulty Easy

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

分析

使用深度优先搜索,沿着树的深度遍历树的节点。

第一种是递归方法

​ 递归调用的参数是通过栈空间传递的,在调用过程中会占用线程的栈资源

并且只有走到最后的结束点函数才能依次退出,在这之前,占用的栈空间一直没有释放

所以如果递归调用次数过多,导致占用的栈资源超过了线程的最大值,那么就会溢出,程序异常

所以考虑使用第二种方法:迭代

利用栈或者队列将递归转化为非递归

题解

1. 递归

/**
 * 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) {
        int ans = dfs(root);
        return ans;
    }
    
    private int dfs(TreeNode root) {
      	// 基准情况
        if (root == null) return 0;
        else {
          	// 左子树的最大深度
            int depth_left = dfs(root.left);
          	// 右子树的最大深度
            int depth_right = dfs(root.right);
            return Math.max(depth_left, depth_right) + 1;
        }
    }
}
复杂度
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度:
    • 最差情况:树完全不平衡,比如每个节点都只有左节点, O ( n ) O(n) O(n)
    • 最好情况:树完全平衡,树高为 l o g ( n ) log(n) log(n),则空间复杂度为 O ( l o g ( n ) ) O(log(n)) O(log(n))

2. 非递归

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
      	// 使用栈来存储节点和深度
        Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
        stack.push(new Pair<>(root, 1));
        int maxDepth = 0;
        while (!stack.isEmpty()) {
            Pair<TreeNode, Integer> pair = stack.pop();
            TreeNode node = pair.getKey();
            maxDepth = Math.max(maxDepth, pair.getValue());
            int currDepth = pair.getValue();
          	// 栈是先进后出,所以先存right,后存left,这样会先计算left节点
            if (node.right != null) {
                stack.push(new Pair<>(node.right, currDepth+1));
            }
            if (node.left != null) {
                stack.push(new Pair<>(node.left, currDepth+1));
            }
        }
        return maxDepth;
    }                           
}

复杂度

  • 时间复杂度: O ( n ) O(n) O(n)

  • 空间复杂度: O ( n ) O(n) O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值