Leetcode每日刷题(十一)

140 阅读1分钟

题目:二叉树的最大深度

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

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

解法一:递归

如果我们知道了左子树和右子树的最大深度 lr,那么该二叉树的最大深度即为 \max(l,r) + 1

public int maxDepth(TreeNode root) {
    return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

复杂度分析:

  • 时间复杂度 O(n) : 其中 n 为二叉树节点的个数。每个节点在递归中只被遍历一次;
  • 空间复杂度 O(height) :其中 \textit{height} 表示二叉树的高度, 递归函数需要栈空间, 而栈空间取决于递归的深度, 因此空间复杂度等价于二叉树的高度。

解法二:广度优先搜索(bfs)

public int maxDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    int ans = 0;
    while (!queue.isEmpty()) {
        // 每层个数
        int size = queue.size();
        while (size > 0) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
            size--;
        }
        ans++;
    }
    return ans;
}

复杂度分析:

  • 时间复杂度 O(n) :其中 n 为二叉树的节点个数。与方法一同样的分析,每个节点只会被访问一次。
  • 空间复杂度:此方法空间的消耗取决于队列存储的元素数量,其在最坏情况下会达到 O(n)

解法三:深度优先搜索(dfs)

public int maxDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
        
    //stack记录的是节点,而level中的元素和stack中的元素
    //是同时入栈同时出栈,并且level记录的是节点在第几层
    Stack<TreeNode> stack = new Stack<>();
    Stack<Integer> level = new Stack<>();
    stack.push(root);
    level.push(1);
    int max = 0;
    while (!stack.isEmpty()) {
        //stack中的元素和level中的元素同时出栈
        TreeNode node = stack.pop();
        int temp = level.pop();
        max = Math.max(temp, max);
        if (node.left != null) {
            //同时入栈
            stack.push(node.left);
            level.push(temp + 1);
        }
        if (node.right != null) {
            //同时入栈
            stack.push(node.right);
            level.push(temp + 1);
        }
    }
    return max;
}