Easy to Understand DFS solution using C#


  • 2
    Y
        Dictionary<int,int> counts = new Dictionary<int,int>();
    
        public int[] FindFrequentTreeSum(TreeNode root) {
            
            FindFrequentSum(root);
            
            int mode = 0;
            int occurence = 0;
            foreach (KeyValuePair<int, int> pair in counts)
            {
    
                if( pair.Value > occurence)
                {
                    occurence = pair.Value;
                    mode = pair.Key;
                }
            }
            
            return (counts.Where(pair => pair.Value == occurence)
                      .Select(pair => pair.Key)).ToArray();
        }
        
        int FindFrequentSum(TreeNode root)
        {
            if(root== null)
                return 0;
           if(root.left == null && root.right == null)
           {
               AddToDictioanry(root.val);
               return root.val;
           }
           int sum = root.val + FindFrequentSum(root.left) + FindFrequentSum(root.right);
           AddToDictioanry(sum);
           return sum;
        }
        
        void AddToDictioanry(int val)
        {
            if(counts.ContainsKey(val))
                counts[val] ++;
            else counts.Add(val,1);
        }
    

Log in to reply
 

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