5ms Java simple inorder traverse solution, I'm not sure whether it didn't use extra space.


  • 3

    Just use inorder traverse and maintain two variables, one for current mode frequency count and the other for global mode frequency count. If we meet a better mode option, clear the current result and add the new one.

    public class Solution {
        public int[] findMode(TreeNode root) {
            if(root==null){
                return new int[0];
            }
            this.cur=new LinkedList<Integer>();
            traverse(root);
            int[] res=new int[cur.size()];
            int i=0;
            Iterator<Integer> itr=cur.iterator();
            while(itr.hasNext()){
                res[i++]=itr.next();
            }
            return res;
        }
        private void traverse(TreeNode root){
            if(root==null){
                return;
            }
            traverse(root.left);
            if(root.val==pre){
                count++;
            }
            else{
                count=1;
            }
            if(count>=max){
                if(count>max){
                    cur.clear();
                }
                max=count;
                if(cur.isEmpty()||root.val!=cur.getLast()){
                    cur.add(root.val);
                }
            }
            pre=root.val;
            traverse(root.right);
        }
        private int max=0, count=0, pre=Integer.MIN_VALUE;
        private LinkedList<Integer> cur;
    }
    

  • 0
    L

    Beautiful solution. The code could be cleaner but still beautiful never the less.


Log in to reply
 

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