import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    // 递归
    // public int maxDepth (TreeNode root) {
    //     // write code here
    //     if(root==null) return 0;
    //     if(root.left==null&&root.right==null) return 1;
    //     return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    // }
    // 非递归的DFS(用栈,Deque是双端队列,既可以作为栈又可以作为队列,取决于使用的方法,这里应当用push,pop)
        // public int maxDepth (TreeNode root) {
        // // write code here
        // if(root==null) return 0;
        // //需要定义两个栈,一个存放元素,一个存放对应的深度
        // Deque<TreeNode> stacke = new LinkedList<>();
        // Deque<Integer> stackd = new LinkedList<>();
        // stacke.push(root);
        // stackd.push(1);
        // int depth = 0;
        // while(!stacke.isEmpty()){
        //     //弹出栈顶元素及其深度
        //     TreeNode currente = stacke.pop();
        //     int currentd = stackd.pop();
        //     depth = Math.max(depth,currentd);
        //     if(currente.right!=null) {
        //         stacke.push(currente.right);
        //         stackd.push(currentd+1);
        //     }
        //     if(currente.left!=null) {
        //         stacke.push(currente.left);
        //         stackd.push(currentd+1);
        //     }
        // }
        // }
        // return depth;
        //BFS(用队列存储,Deque是双端队列,既可以作为栈又可以作为队列,取决于使用的方法,这里应当用add,poll)
        public int maxDepth (TreeNode root) {
        // write code here
        if(root==null) return 0;
        //需要定义两个栈,一个存放元素,一个存放对应的深度
        Deque<TreeNode> queuee = new LinkedList<>();
        Deque<Integer> queued = new LinkedList<>();
        queuee.add(root);
        queued.add(1);
        int depth = 0;
        while(!queuee.isEmpty()){
            //弹出栈顶元素及其深度
            TreeNode currente = queuee.poll();
            int currentd = queued.poll();
            depth = Math.max(depth,currentd);
            if(currente.left!=null) {
                queuee.add(currente.left);
                queued.add(currentd+1);
            }
            if(currente.right!=null) {
                queuee.add(currente.right);
                queued.add(currentd+1);
            }
        }
        return depth;
        }
}