Simulate Recursive Tree Traversal
You are required to simulate a recursive depth-first binary-tree traversal exactly, but you must implement it using an iterative algorithm with an explicit stack.
The recursive behaviour you must reproduce is defined as follows:
- A function visit(u, depth) returns immediately if u == -1 (a null node).
- Otherwise, it prints "ENTER u depth".
- It recursively calls visit(left_child, depth + 1).
- It recursively calls visit(right_child, depth + 1).
- Finally, it prints "EXIT u depth".
- The initial call is visit(root, 0).
You must implement a class TreeTraversalSimulator with a single method:
- simulate(int root, vector<vector<int>>& children): Takes the root node ID and a children matrix. Each row i in the children matrix corresponds to node i and contains exactly 2 integers representing its left and right child IDs, respectively. A child ID of -1 indicates no child.
The method must directly return a vector<string>, where each element in the vector is a single log statement (e.g., "ENTER 0 0" is one string in the array). The sequence must contain all "ENTER" and "EXIT" logs exactly as they would be printed.
The final string in the returned vector must be "DEPTH d", where d is the maximum number of simultaneously active non-null visit calls in the equivalent recursive traversal (this is equivalent to the peak size of your explicit stack of valid nodes).
For an empty tree (e.g., root = -1), the method should return a vector with a single string: ["DEPTH 0"].
Example 1:
Input: root = 0, child = [[1, 2], [-1, -1], [-1, -1]]
Output: ["ENTER 0 0", "ENTER 1 1", "EXIT 1 1", "ENTER 2 1", "EXIT 2 1", "EXIT 0 0", "DEPTH 2"]
Explanation:
- n=3, root=0. Node 0 has left child 1 and right child 2. Nodes 1 and 2 are leaves.
- visit(0, 0) -> Stack size 1. Adds "ENTER 0 0".
- visit(1, 1) -> Stack size 2. Adds "ENTER 1 1". Left/right return immediately. Adds "EXIT 1 1".
- visit(2, 1) -> Stack size 2. Adds "ENTER 2 1". Left/right return immediately. Adds "EXIT 2 1".
- Adds "EXIT 0 0".
- The peak number of active non-null frames simultaneously was 2. Final element is "DEPTH 2".
Example 2:
Input: root = -1, child = []
Output: ["DEPTH 0"]
Explanation:
- n=0, root=-1. The tree is completely empty.
- No visit calls are made for valid nodes.
- The returned vector is simply ["DEPTH 0"].
Now Your Turn!
Pick the correct output for the given inputInput: root = 0, child = [[-1, -1]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 0 <= n <= 2e5
- -1 <= root < n
- -1 <= left_child[i], right_child[i] < n
- The input is guaranteed to form a valid binary tree containing exactly n nodes. You must use an explicit stack. Deep recursion on a chain of 200,000 nodes will cause a Stack Overflow (Memory Limit Exceeded / Runtime Error).