flatten-binary-tree-to-linked-list.dart (898B)
1 //Given a binary tree the values after performing a preorder 2 //traversal and then reorganizing the tree so that the preorder 3 //values are all placed on the right side similar to a linked list. 4 //To do this I iterated through the tree adding each node to the list 5 //as I went (pre-order). I then created a new binary tree reusing the root 6 //where each right value was the next value in the list. 7 //Time: 285ms Beats: 100% 8 //Memory: 143.8MB Beats: 50% 9 10 class Solution { 11 List<int> vals = []; 12 void flatten(TreeNode? root) { 13 recurse(root); 14 root?.left = null; 15 TreeNode? itr = root; 16 for(int i = 1 ; i < vals.length ; ++i){ 17 itr?.right = new TreeNode(vals[i]); 18 itr = itr?.right; 19 } 20 21 } 22 void recurse(TreeNode? root){ 23 if(root == null){ 24 return; 25 } 26 vals.add(root.val); 27 recurse(root.left); 28 recurse(root.right); 29 } 30 }