leetcode

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

binary-tree-right-side-view.dart (1182B)


      1 //Given the root of a binary tree return all of the values
      2 //contained within the nodes if someone were looking at the tree from the right side.
      3 //Ex:
      4 //      1 <-
      5 //     2 3 <-
      6 //    3 4 <-
      7 //   6 <-
      8 //    4 <-
      9 //The time complexity of this code is O(n) where n is the
     10 //number of nodes in the list. My solution uses BFS and after
     11 //each layer is traversed it returns the rightmost node's value.
     12 //Time: 293ms Beats: 50%
     13 //Memory: 145MB Beats: 100%
     14 
     15 class Solution {
     16   List<int> rightSideView(TreeNode? root) {
     17     if(root == null){
     18       return [];
     19     }
     20       List<TreeNode?> queue = [];
     21       queue.add(root);
     22       List<int> return_list = [];
     23       return_list.add(root?.val ?? 0);
     24       while(queue.length != 0){
     25         int init_length = queue.length;
     26         for(int i = 0 ; i < init_length ; ++i){
     27           
     28           if(queue[0]?.left != null){
     29             queue.add(queue[0]?.left);
     30           }
     31           if(queue[0]?.right != null){
     32             queue.add(queue[0]?.right);
     33           }
     34           queue.removeAt(0);
     35         }
     36         if(queue.length != 0){
     37           return_list.add((queue[queue.length - 1]?.val ?? 0));
     38         }
     39       }
     40       return return_list;
     41   }
     42 }