leetcode

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

increasing-order-search-tree.dart (997B)


      1 //Given a tree return the inorder traversal as a binary tree
      2 //where all elements are in order to the right.
      3 
      4 //Ex.
      5 //  2
      6 // 1 3
      7 //Output:
      8 //1
      9 // 2
     10 //  3
     11 
     12 //My solution does an inorder traversal first then builds
     13 //a new tree that does the O(n) search tree creation.
     14 //Time: 269ms Beats: 100%
     15 //Memory: 142.8MB
     16 
     17 class Solution {
     18   TreeNode? increasingBST(TreeNode? root) {
     19       List<int> treeVals = [];
     20       traverse(root,treeVals);
     21       root = new TreeNode(treeVals[0]);
     22       treeVals.removeAt(0);
     23       return stupidTree(root,treeVals);
     24      
     25   }
     26   TreeNode? stupidTree(TreeNode? root, List<int> treeVals){
     27     if(treeVals.length == 0){
     28       return root;
     29     }
     30     root?.right = TreeNode(treeVals[0]);
     31     treeVals.removeAt(0);
     32     stupidTree(root?.right, treeVals);
     33     return root;
     34   }
     35   void traverse(TreeNode? root, List<int> treeVals){
     36       if(root != null){
     37         traverse(root.left, treeVals);
     38         treeVals.add(root.val);
     39         traverse(root.right, treeVals);
     40       }
     41   }
     42 }