Java Recursion Solution, no map, no second round


  • 0
    S
    Public class Solution {
        List<Integer> list;
        int max;
        int currval;
        int currcount;
        
        public int[] findMode(TreeNode root) {
            if(root == null) return new int[0];
            currval =0;
            currcount = 0;
            helper(root);
            int[] res = new int[list.size()];
            for(int i = 0; i<res.length; i++) res[i] = list.get(i);
            return res;
        }
        
        public void helper(TreeNode root) {
            if (root == null) return;
            helper(root.left);
            if(root.val == currval) {
                currcount ++;
            } else {
                currcount = 1;
                currval = root.val;
            }
            if (currcount > max) {
                max = currcount;
                list = new ArrayList<>();
                list.add(root.val);
            } else if(currcount == max) {
                list.add(root.val);
            }
            helper(root.right);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.