Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
Solution:

/**
 * 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 {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        int[] maxDepth = new int[]{1};
        pre(root, result, 1, maxDepth);
        return result;
    }
    
    private void pre(TreeNode root, List<Integer> result, int depth, int[] maxDepth) {
        if (root == null) {
            return;
        }
        if (depth >= maxDepth[0]) {
            result.add(root.val);
        }
        maxDepth[0] = Math.max(maxDepth[0], depth + 1);
        if (root.right != null) {
            pre(root.right, result, depth + 1, maxDepth);
        } 
        if (root.left != null) {
            pre(root.left, result, depth + 1, maxDepth);
        }
    }
}