Java solution using using two pass Inorder

  • 0
    public int[] findMode(TreeNode root) {
            // [0] - prev val, [1] = current count, [2] max count 
            int[] placeHolder = new int[3];
            // inorder since this is a a BST
            // running first time to find the max ocurrence of a node
            inorder(root, placeHolder, null);
            List<Integer> resultList = new ArrayList<Integer>();
            // reseting the current count and prev val
            placeHolder[0] = 0;
            placeHolder[1] = 0;
            // running second time to get all the repeating node with same occurence frequency
            inorder(root, placeHolder, resultList);
            // storing the value in an array from list.
            int[] result = new int[resultList.size()];
            for(int i=0; i<result.length; i++){
                result[i] = resultList.get(i);
            return result;
        private void inorder(TreeNode node, int[] placeHolder, List<Integer> resultList){
            if(node == null){
            // traversing left node first
            inorder(node.left, placeHolder, resultList);
            // if prev value is same as current value increase current count by 1
            if(placeHolder[0] == node.val){
            // else set prev value to currnt and make the currenct count = 1
                placeHolder[1] = 1;
                placeHolder[0] = node.val;
            // if current count is greater than max frequency then update max frequency to current count
            if(placeHolder[1] > placeHolder[2]){
                placeHolder[2] = placeHolder[1];
            // if the input list is not null and current count is same as max frequency then record current node
            if(placeHolder[2] == placeHolder[1] && resultList != null){
            // traversing right node
            inorder(node.right, placeHolder, resultList);

Log in to reply

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