Java inorder recursive solution beats 99% with explanation


  • 2
    S

    Idea: Duplicated numbers must be consecutive in the inorder traversal.

    // Duplicated number of this node must be the largest in left subtree (right most) or the smallest in the right subtree (left most)
    // Right most in left tree, visited just before this node
    // Left most in right tree, visited just after this node */
        
        int preNode = 0;
        int max = 0;
        int currMax = 0;
        public int[] findMode(TreeNode root) {
            HashSet<Integer> set = new HashSet<>();
            findMode_helper(root, set);
            Iterator<Integer> it = set.iterator();
            int[] result = new int[set.size()];
            int i = 0;
            while(it.hasNext()) {
                result[i] = it.next();
                i++;
            }
            return result;
        }
        
        private void findMode_helper(TreeNode root, HashSet<Integer> set) {
            if (root == null) return;
            findMode_helper(root.left, set); // after visiting left subtree, preNode is the right most node in the left subtree
            if (preNode == root.val) {
                currMax++;
            } else {
                currMax = 1;
            }
            if (currMax >= max) {
                if (currMax > max) {
                    set.clear();
                }
                max = currMax;
                set.add(root.val);
            }
            preNode = root.val; // this node will be visited just before the left most node in the right subtree
            findMode_helper(root.right, set);
        }
    

Log in to reply
 

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