Morris solution without helper function


  • 0
    C
        public int[] findMode(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            TreeNode node = root;
            int maxcnt = 0;
            int currcount = 0;
            int currvalue = Integer.MAX_VALUE;
            while(node != null){
                if(node.left != null){
                    TreeNode rightmost = node.left;
                    while(rightmost.right != null && rightmost.right != node){
                        rightmost = rightmost.right;
                    }
                    if(rightmost.right == null){
                        rightmost.right = node;
                        node = node.left;
                    }else{
                        if(currvalue == node.val){
                            currcount ++;
                            if(currcount > maxcnt){
                                list.clear();
                                list.add(currvalue);
                                maxcnt = currcount;
                            }else if(currcount == maxcnt){
                                list.add(currvalue);
                            }
                        }else{
                            currvalue = node.val;
                            currcount = 1;
                            if(currcount == maxcnt){
                                list.add(currvalue);
                            }
                        }
                        node = node.right;
                    }
                }else{
                    if(currvalue == Integer.MAX_VALUE){
                        currvalue = node.val;
                        maxcnt = 1;
                        currcount = 1;
                        list.add(currvalue);
                    }else{
                        if(currvalue == node.val){
                            currcount ++;
                            if(currcount > maxcnt){
                                list.clear();
                                list.add(currvalue);
                                maxcnt = currcount;
                            }else if(currcount == maxcnt){
                                list.add(currvalue);
                            }
                        }else{
                            currvalue = node.val;
                            currcount = 1;
                            if(currcount == maxcnt){
                                list.add(currvalue);
                            }
                        }
                    }
                    node = node.right;
                }
            }
            int[] res = new int[list.size()];
            for(int i = 0 ;i < res.length; i++){
                res[i] = list.get(i);
            }
            return res;
        }

Log in to reply
 

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