# 1. 题目

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

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

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

示例:
给定二叉树 [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() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // private static int count;
    public int maxDepth(TreeNode root) {
        // count = 0;
        if(root == null){
            return 0;
        }
        if(root.left == null && root.right == null){
            return 1;
        }
        return dfs(root, 2);
    }
    int dfs(TreeNode cur, int count){
        
        if(cur == null ) {
            return 0;
        }
        if(cur.left != null ){
            count =  1;
        }
        if(cur.right != null){
            count = 1;
        }
        return Math.max(count + dfs(cur.left, count), count +dfs(cur.right, count));
    }
}

时间复杂度:O (n),每个结点只被访问一次。

空间复杂度:O (height),递归高度。

# 3. 官方题解

# 1. 深度优先搜索

如果知道左子树和右子树的最大深度 l,r,那么二叉树的最大深度为:max(l,r)+ 1

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}

# 2. 广度优先算法

使用队列存放当前层的所有结点,直到当前层没有结点,遍历的队列的次数就是树的深度。

class Solution {
    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)。