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:
- The number of nodes in the given tree will be between 1 and 100.
- Each node will have a unique integer value from 0 to 1000.
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); } }
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 :(
ReplyDeleteclass 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;
}
};