leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

mode-of-binary-tree.dart (1377B)


      1 //Given a binary search tree find the mode value(s) and
      2 //return it in a list. To solve this problem I iterated through
      3 //the tree and added each value to a map where the value was the number
      4 //of instances of a given number. Then I iterated through the map
      5 //to find the value with the highest number of occurences and returned 
      6 //the associated key.
      7 //The time complexity of this code is O(n) where n is the number of nodes.
      8 //Time: 307ms Beats: 100%
      9 //Memory: 145.7MB Beats: 100%
     10 //Not enough submissions for comparsion metrics.
     11 
     12 /**
     13  * Definition for a binary tree node.
     14  * class TreeNode {
     15  *   int val;
     16  *   TreeNode? left;
     17  *   TreeNode? right;
     18  *   TreeNode([this.val = 0, this.left, this.right]);
     19  * }
     20  */
     21 class Solution {
     22   List<int> findMode(TreeNode? root) {
     23       int usages = 0;
     24       List<int> return_vals = [0];
     25       recurse(root);
     26       for(var entries in vals.entries){
     27           if(entries.value > usages){
     28               usages = entries.value;
     29               return_vals = [entries.key];
     30           }
     31           else if(entries.value == usages){
     32               return_vals.add(entries.key);
     33           }
     34       }
     35       return return_vals;
     36   }
     37   Map<int, int> vals = {};
     38 
     39   void recurse(TreeNode? root){
     40       if(root == null){
     41           return;
     42       }
     43       vals[root.val] = (vals[root.val] ?? 0) + 1;
     44       recurse(root.left);
     45       recurse(root.right);
     46   }
     47 }