leetcode

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

same-tree.dart (1224B)


      1 //Iterate through tree and determine if it is equal to 
      2 //another tree. This algorithm has a worst case time complexity of
      3 //O(n) where n is the length of the list. Because for
      4 //each node it is visited one time and then each node
      5 //is again compared to the corresponding node from the
      6 //other tree.
      7 //Runtime: 262ms Beats: 50%
      8 //Memory: 142.6MB Beats: 43.75%
      9 
     10 class TreeNode{
     11     int val;
     12     TreeNode? left;
     13     TreeNode? right;
     14 }
     15 
     16 class Solution {
     17   List<int?> l1 = [];
     18   List<int?> l2 = [];
     19   bool isSameTree(TreeNode? p, TreeNode? q) {
     20     recurse(p , 1);
     21     recurse(q , 2);
     22     if(l2.length != l1.length){
     23         return false;
     24     }
     25     bool equal = true;
     26       for(int i = 0; i < l1.length ; ++i){
     27         if(l1[i] != l2[i]){
     28           equal = false;
     29           break;
     30       }
     31   }
     32       return equal;
     33   }
     34   void recurse(TreeNode? node, int list_num){
     35 
     36       if(node == null){
     37           if(list_num == 1){
     38               l1.add(null);
     39           }
     40           else{
     41               l2.add(null);
     42           }
     43           return;
     44       }
     45       recurse(node.left , list_num);
     46       recurse(node.right, list_num);
     47       if(list_num == 1){
     48           l1.add(node.val);
     49       }
     50       else{
     51           l2.add(node.val);
     52       }
     53   }
     54 }