LeetCode 104. Maximum Depth of Binary Tree

解法一 Recursion

思路

使用一个 global variable - max 来记录最大的深度,并在 DFS 递归函数中持续更新 max 的值。但由于 int 类型的变量在函数调用中是 pass by value 的,所以我用一个整型数组来储存最大的那个值,这样数值就可以在函数调用中传递了。

我使用了中序遍历来实现 DFS。

代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] max = new int[1];
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        findDepth(1, root);
        return max[0];
    }

    private void findDepth(int depth, TreeNode node) {
        if (node == null) {
            return;
        }

        findDepth(depth + 1, node.left);
        max[0] = Math.max(max[0], depth);
        findDepth(depth + 1, node.right);
    }
}
复杂度分析
  • 时间复杂度
    • O(n),因为遍历了树的所有元素。
  • 空间复杂度
    • O(H),取决于树的高度。

解法二 Iteration

思路

简单来说就是做一个 level-order traversal, 最后记录最后一层的层数。

代码
/**
 * 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;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int level = 0;
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            level++;
        }

        return level;
    }
}
复杂度分析
  • 时间复杂度
    • O(n),BFS 遍历了每一个元素
  • 空间复杂度
    • O(n),keep the nodes in the tree
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!