Inoder


  • 0
    X
    private final List<Integer> modes = new ArrayList<>();
    private TreeNode pre;
    private int occurs = 0;
    private int maxOccurs = 0;
    
    public int[] findMode(TreeNode root) {
        inorder(root);
        return modes.stream().mapToInt(i -> i).toArray();
    }
    
    private void inorder(TreeNode root) {
        if (root == null) {
            return;
        }
        
        inorder(root.left);
        
        if (pre != null && pre.val == root.val) {
            occurs += 1;
        } else {
            occurs = 1;
        }
        
        if (occurs == maxOccurs) {
            modes.add(root.val);
        } else if (occurs > maxOccurs) {
            modes.clear();
            modes.add(root.val);
            maxOccurs = occurs;
        }
    
        pre = root;
        inorder(root.right);
    }
    

Log in to reply
 

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