Populate Inorder successor of all nodes

Pattern: Floor and ceil

medium

Walk the tree in reverse inorder (right, node, left), remembering the node visited just before. That node is the next one in normal inorder, so it is the current node's successor.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

For every node, find its inorder successor's value (-1 for the last node). The GFG version stores it in a next pointer on each node; this guide returns the successors as a list in level order of the nodes. The example gives [12, 10, -1, 8]. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Which node comes right after another in inorder?
  • If you walk backwards (right, node, left), what do you have just before each node?
  • What does the last node get?

Hints

    Brute force, and why it fails

    Collect the inorder into a list and pair neighbours: O(n) with an extra list.

    The key insight

    Reverse inorder visits nodes from last to first, so the previously visited node is always the next one.

    Dry run

    after-1

    Tree [10, 8, 12, 3]. Reverse inorder visits 12, 10, 8, 3.

    Step 1 of 3

    The plan

    after = -1
    fill(n): if null: return; fill(n.right); next[n] = after; after = n.val; fill(n.left)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One walk plus the map and the level-order report.

    Edge cases

    • One node: [-1].
    • A chain.
    • Empty tree.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> successors(TreeNode root) {
            Map<TreeNode, Integer> next = new HashMap<>();
            int[] after = {-1};                     // the value visited just before, in reverse inorder
            fill(root, next, after);
            List<Integer> out = new ArrayList<>();  // report in level order
            Queue<TreeNode> q = new ArrayDeque<>();
            if (root != null) q.add(root);
            while (!q.isEmpty()) {
                TreeNode n = q.poll();
                out.add(next.get(n));
                if (n.left != null) q.add(n.left);
                if (n.right != null) q.add(n.right);
            }
            return out;
        }
    
        private void fill(TreeNode n, Map<TreeNode, Integer> next, int[] after) {   // right, node, left
            if (n == null) return;
            fill(n.right, next, after);
            next.put(n, after[0]);                  // the node visited just before this one comes next in inorder
            after[0] = n.val;
            fill(n.left, next, after);
        }
    }

    C++

    class Solution {
    public:
        vector<int> successors(TreeNode* root) {
            unordered_map<TreeNode*, int> next;
            int after = -1;                         // the value visited just before, in reverse inorder
            fill(root, next, after);
            vector<int> out;                        // report in level order
            queue<TreeNode*> q;
            if (root != NULL) q.push(root);
            while (!q.empty()) {
                TreeNode* n = q.front();
                q.pop();
                out.push_back(next[n]);
                if (n->left != NULL) q.push(n->left);
                if (n->right != NULL) q.push(n->right);
            }
            return out;
        }
    
        void fill(TreeNode* n, unordered_map<TreeNode*, int>& next, int& after) {   // right, node, left
            if (n == NULL) return;
            fill(n->right, next, after);
            next[n] = after;                        // the node visited just before this one comes next in inorder
            after = n->val;
            fill(n->left, next, after);
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def successors(self, root) -> list[int]:
            nxt, after = {}, -1                     # after: the value visited just before, in reverse inorder
    
            def fill(n):                            # right, node, left
                nonlocal after
                if n:
                    fill(n.right)
                    nxt[n] = after                  # the node visited just before this one comes next in inorder
                    after = n.val
                    fill(n.left)
    
            fill(root)
            out, q = [], deque([root] if root else [])   # report in level order
            while q:
                n = q.popleft()
                out.append(nxt[n])
                q.extend(c for c in (n.left, n.right) if c)
            return out

    Common mistakes

    • Walking in normal inorder, which gives predecessors.
    • Updating after before storing it.

    Similar problems