104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example:
Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

二叉树最大深度等于层数(从1开始算)

Solution 1: DFS, preorder O(n); O(h)
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); //preorder
    }
Solution 2: BFS O(n); O(w)
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int max = 0; //这里是0,和求minDepth不一样
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            max++;
        }
        return max;
    }

results matching ""

    No results matching ""