Leetcode

Increasing Order Search Tree

  • Time:O(n)
  • Space:O(h)

C++

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

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

JAVA

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;
  }
}

Python

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