Increasing Order Search Tree — LeetCode 897 Python Solution

EasyStackTreeDepth-First SearchBinary Search TreeBinary Tree
Problem
#897
Pattern
Stack
Reading time
4 min

The problem

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

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]

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:
        def dfs(root):
            if root is None:
                return
            nonlocal prev
            dfs(root.left)
            prev.right = root
            root.left = None
            prev = root
            dfs(root.right)

        dummy = prev = TreeNode(right=root)
        dfs(root)
        return dummy.right

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 897. Increasing Order Search Tree is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 897. Increasing Order Search Tree?
LeetCode 897. Increasing Order Search Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 897. Increasing Order Search Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 897. Increasing Order Search Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 897. Increasing Order Search Tree cover?
LeetCode 897. Increasing Order Search Tree is tagged Stack, Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview