Leetcode 897. Increasing Order Search Tree
Given the root of a binary search 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 one right child.
To solve this problem, we will employ an in-order traversal to visit the nodes of the tree in ascending order. During the traversal, we will rebuild the tree such that each node only has a right child.
Here is the step-by-step approach:
To implement this, we’ll maintain a dummy node that helps in reconstructing the tree. We will use a current pointer that starts at the dummy node and moves right as we attach nodes to the new tree.
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* increasingBST(TreeNode* root) {
if (!root) return nullptr;
TreeNode* dummy = new TreeNode(0);
TreeNode* current = dummy;
inorderTraversal(root, current);
return dummy->right;
}
private:
void inorderTraversal(TreeNode* node, TreeNode*& current) {
if (!node) return;
inorderTraversal(node->left, current);
// At this point, node is the next node in inorder sequence
node->left = nullptr; // We do not need left children in the new tree
current->right = node; // Attach current's right to node
current = node; // Move current
inorderTraversal(node->right, current);
}
};
// Helper function to create a new TreeNode
TreeNode* createNode(int val) {
return new TreeNode(val);
}
// Helper function to print the resulting tree (for testing)
void printRightSkewedTree(TreeNode* root) {
TreeNode* current = root;
while (current) {
std::cout << current->val << " ";
current = current->right;
}
}
int main() {
// Example usage
Solution sol;
TreeNode* root = createNode(5);
root->left = createNode(3);
root->right = createNode(6);
root->left->left = createNode(2);
root->left->right = createNode(4);
root->left->left->left = createNode(1);
root->right->right = createNode(8);
root->right->right->left = createNode(7);
root->right->right->right = createNode(9);
TreeNode* result = sol.increasingBST(root);
printRightSkewedTree(result);
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?