LeetCode Solutions

897. Increasing Order Search Tree

Time: $O(n)$

Space: $O(h)$

			

class Solution {
 public:
  TreeNode* increasingBST(TreeNode* root, TreeNode* tail = nullptr) {
    if (root == nullptr)
      return tail;

    TreeNode* ans = increasingBST(root->left, root);
    root->left = nullptr;
    root->right = increasingBST(root->right, tail);
    return ans;
  }
};
			

class Solution {
  public TreeNode increasingBST(TreeNode root) {
    return increasingBST(root, null);
  }

  private TreeNode increasingBST(TreeNode root, TreeNode tail) {
    if (root == null)
      return tail;

    TreeNode ans = increasingBST(root.left, root);
    root.left = null;
    root.right = increasingBST(root.right, tail);
    return ans;
  }
}
			

class Solution:
  def increasingBST(self, root: TreeNode, tail: TreeNode = None) -> TreeNode:
    if not root:
      return tail

    res = self.increasingBST(root.left, root)
    root.left = None
    root.right = self.increasingBST(root.right, tail)
    return res