Increasing BST, by Leetcode

Problem is here: https://leetcode.com/problems/increasing-order-search-tree/description/

Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]

       5
      / \
    3    6
   / \    \
  2   4    8
 /        / \ 
1        7   9

Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

 1
  \
   2
    \
     3
      \
       4
        \
         5
          \
           6
            \
             7
              \
               8
                \
                 9  
Note:
  1. The number of nodes in the given tree will be between 1 and 100.
  2. Each node will have a unique integer value from 0 to 1000.
Even though the problem does not mention a BST, it "implies" a BST since in the signature of the function in the coding area is called "IncreasingBST". Solution is to perform an in-order traversal of the tree, and in the "current" processing (remember in-order: left -> current -> right) build the new tree exactly as described by the problem. Code is below, cheers, Boris.

 public class Solution
 {
  public TreeNode IncreasingBST(TreeNode root)
  {
   TreeNode retVal = null;
   TreeNode current = null;
   IncreasingBST(root, ref current, ref retVal);
   return retVal;
  }

  private void IncreasingBST(TreeNode root, ref TreeNode current, ref TreeNode retVal)
  {
   if (root == null) return;
   IncreasingBST(root.left, ref current, ref retVal);
   if (current == null)
   {
    current = new TreeNode(root.val);
    retVal = current;
   }
   else
   {
    current.right = new TreeNode(root.val);
    current = current.right;
   }
   IncreasingBST(root.right, ref current, ref retVal);
  }
 }

Comments

  1. Well done! I really like the fact that you don't modify the original tree, but in pursuit of speed my version is actually mutating the original tree :(

    class Solution {
    private:
    TreeNode* start = nullptr;
    TreeNode* prev = nullptr;

    public:
    TreeNode* increasingBST(TreeNode* root) {
    if (!root) return nullptr;
    increasingBST(root->left);
    if (!start) start = root;
    if (prev) prev->right = root;
    root->left = nullptr;
    prev = root;
    increasingBST(root->right);
    return start;
    }
    };

    ReplyDelete

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons