Flatten BST to sorted list

Pattern: BST iterator

medium

Walk the BST inorder and hang each node on the right of the previous one, clearing its left pointer. The result is a right-going chain in increasing order. A dummy node before the first one avoids a special case.

The problem

Rearrange the BST in place into a chain of right children holding the values in increasing order, with no left children, and return the new root. LeetCode's Increasing Order Search Tree is the same task. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • In what order must the chain run?
  • What do you need to remember during the walk?
  • Is it safe to clear a node's left pointer when you visit it?

Hints

    Brute force, and why it fails

    Collect nodes in a list, then relink: O(n) extra memory.

    The key insight

    Inorder visits nodes in chain order, so linking each to the previous one in the same walk builds the chain.

    Dry run

    order2 3 4 5 6 7 8

    BST [5, 3, 7, 2, 4, 6, 8]. Inorder visits 2, 3, 4, 5, 6, 7, 8.

    Step 1 of 3

    The plan

    prev = dummy
    inorder(n): inorder(n.left); n.left = null; prev.right = n; prev = n; inorder(n.right)
    return dummy.right
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One walk.

    Edge cases

    • Empty tree.
    • One node.
    • A tree that is a chain, where h = n.
    I've built my logic, show the code

    Java

    class Solution {
        private TreeNode prev;
    
        public TreeNode flatten(TreeNode root) {
            TreeNode dummy = new TreeNode(0);
            prev = dummy;
            inorder(root);
            return dummy.right;
        }
    
        private void inorder(TreeNode n) {          // in sorted order, hang each node on the previous one's right
            if (n == null) return;
            inorder(n.left);
            n.left = null;
            prev.right = n;
            prev = n;
            inorder(n.right);
        }
    }

    C++

    class Solution {
    public:
        TreeNode* prev;
    
        TreeNode* flatten(TreeNode* root) {
            TreeNode dummy(0);
            prev = &dummy;
            inorder(root);
            return dummy.right;
        }
    
        void inorder(TreeNode* n) {                 // in sorted order, hang each node on the previous one's right
            if (n == NULL) return;
            inorder(n->left);
            n->left = NULL;
            prev->right = n;
            prev = n;
            inorder(n->right);
        }
    };

    Python

    from lib import TreeNode
    
    
    class Solution:
        def flatten(self, root):
            dummy = prev = TreeNode(0)
    
            def inorder(n):                         # in sorted order, hang each node on the previous one's right
                nonlocal prev
                if n:
                    inorder(n.left)
                    n.left = None
                    prev.right = n
                    prev = n
                    inorder(n.right)
    
            inorder(root)
            return dummy.right

    Common mistakes

    • Forgetting to clear left pointers.
    • Returning the old root.

    Similar problems