import java.util.*;
public class Main {
    public static 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;
        }
    }
    // Same Solution class as LeetCode
    static class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null)
                return 0;
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            return Math.max(left, right) + 1;
        }
    }
    // Function to build tree from level-order array
    static TreeNode buildTree(Integer[] arr) {
        if (arr.length == 0 || arr[0] == null)
            return null;
        TreeNode root = new TreeNode(arr[0]);
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int i = 1;
        while (!q.isEmpty() && i < arr.length) {
            TreeNode curr = q.poll();
            // Left child
            if (i < arr.length && arr[i] != null) {
                curr.left = new TreeNode(arr[i]);
                q.offer(curr.left);
            }
            i++;
            // Right child
            if (i < arr.length && arr[i] != null) {
                curr.right = new TreeNode(arr[i]);
                q.offer(curr.right);
            }
            i++;
        }
        return root;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Enter number of elements
        int n = sc.nextInt();
        Integer[] arr = new Integer[n];
        // Enter elements (use "null" for missing nodes)
        for (int i = 0; i < n; i++) {
            String s = sc.next();
            if (s.equals("null"))
                arr[i] = null;
            else
                arr[i] = Integer.parseInt(s);
        }
        TreeNode root = buildTree(arr);
        Solution obj = new Solution();
        System.out.println("Maximum Depth = " + obj.maxDepth(root));
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: