C# recursive no dictionary/map, possibly constant space


  • 0
    H
    public int[] FindMode(TreeNode root) {
            List<int> modes = new List<int>();
            int modeCount = 0, lastValue = int.MinValue, lastValueCount = 0;
            Recurse(root, modes, ref modeCount, ref lastValue, ref lastValueCount);
            
            return modes.ToArray();
        }
        
        public void Recurse(TreeNode root, List<int> modes, ref int modeCount, ref int lastValue, ref int lastValueCount) {
            if (root == null) return;
            Recurse(root.left, modes, ref modeCount, ref lastValue, ref lastValueCount);
            
            if (root.val == lastValue) {
                lastValueCount++;
            } else {
                lastValue = root.val;
                lastValueCount = 1;
            }
            
            if (lastValueCount > modeCount) {
                modes.Clear();
                modes.Add(root.val);
                modeCount = lastValueCount;
            } else if (lastValueCount == modeCount) {
                modes.Add(root.val);
            }
            
            Recurse(root.right, modes, ref modeCount, ref lastValue, ref lastValueCount);
        }
    

Log in to reply
 

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