Algorithm
Problem Name: 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.
Example 1:
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:
Input: root = [5,1,7] Output: [1,null,5,null,7]
Constraints:
- The number of nodes in the given tree will be in the range
[1, 100]
. 0 <= Node.val <= 1000
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public TreeNode increasingBST(TreeNode root) {
Stack stack = new Stack<>();
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode newHead = null;
while (!stack.isEmpty()) {
TreeNode removed = stack.pop();
if (newHead == null) {
newHead = removed;
}
TreeNode rightNode = removed.right;
while (rightNode != null) {
stack.push(rightNode);
rightNode = rightNode.left;
}
removed.right = stack.isEmpty() ? null : stack.peek();
removed.left = null;
}
return newHead;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const increasingBST = function(root) {
return helper(root, null)
};
function helper(node, tail) {
if(node == null) return tail
const res = helper(node.left, node)
node.left = null
node.right = helper(node.right, tail)
return res
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def increasingBST(self, root, tail = None):
if not root: return tail
res = self.increasingBST(root.left, root)
root.left = None
root.right = self.increasingBST(root.right, tail)
return res
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0897_IncreasingOrderSearchTree
{
private TreeNode currentRoot;
public TreeNode IncreasingBST(TreeNode root)
{
var dummy = new TreeNode(-1);
currentRoot = dummy;
InOrder(root);
return dummy.right;
}
private void InOrder(TreeNode node)
{
if (node == null) return;
InOrder(node.left);
node.left = null;
currentRoot.right = node;
currentRoot = node;
InOrder(node.right);
}
}
}
Copy The Code &
Try With Live Editor
Input
Output