DFS 和 BFS都可以

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if(root == null){
            return 0;
        }
        Stack<TreeNode> s = new Stack<>();
        Stack<Integer> level = new Stack<>();
        s.push(root);
        level.push(1);
        int max = 0;
        while(!s.isEmpty()){
            TreeNode t = s.pop();
            int flag = level.pop();
            max = Math.max(max,flag);
            if(t.left != null){
                s.push(t.left);
                level.push(flag+1);
            }
            if(t.right != null){
                s.push(t.right);
                level.push(flag+1);
            }       
        }
        return max;
    }
}