zig-zag-level-order.dart (1414B)
1 //Traverse a binary tree and return a list that contains 2 //one list for each layer. As you make your way down the tree 3 //start going from left to right and then from right to left and so on. 4 //The time complexity of this code is O(n) where n is the 5 //number of nodes in the tree. 6 //Time: 264ms Beats: 63.64% 7 //Memory: 143.1MB Beats: 54.55% 8 9 /** 10 * Definition for a binary tree node. 11 * class TreeNode { 12 * int val; 13 * TreeNode? left; 14 * TreeNode? right; 15 * TreeNode([this.val = 0, this.left, this.right]); 16 * } 17 */ 18 class Solution { 19 List<List<int>> zigzagLevelOrder(TreeNode? root) { 20 if(root == null){ 21 return []; 22 } 23 List<TreeNode?> queue = []; 24 List<List<int>> return_list = []; 25 queue.add(root); 26 int row = 0; 27 while(queue.length > 0){ 28 return_list.add([]); 29 int init_length = queue.length; 30 for(int i = 0 ; i < init_length ; ++i){ 31 if(queue[0]?.left != null){ 32 queue.add(queue[0]?.left); 33 } 34 if(queue[0]?.right != null){ 35 queue.add(queue[0]?.right); 36 } 37 return_list[return_list.length - 1].add((queue[0]?.val ?? 0)); 38 queue.removeAt(0); 39 } 40 row += 1; 41 } 42 43 for(int i = 1 ; i < return_list.length ; i += 2){ 44 return_list[i] = return_list[i].reversed.toList(); 45 } 46 47 48 49 return return_list; 50 51 } 52 53 }