Problems178
Search for a command to run...
All traversals in a single pass using a stack
Current step
Start Traversals. Initialize empty arrays and stack.
Stack with State Variable
1class Solution {2 treeTraversal(root) {3 // Arrays to store the traversals4 let pre = [], inOrder = [], post = [];5 6 // If the tree is empty, return empty traversals7 if (root === null) return [pre, inOrder, post];8 9 // Stack to maintain nodes and their traversal state10 let stack = [[root, 1]];11 12 while (stack.length > 0) {13 // Get the top element from the stack14 let [node, state] = stack.pop();15 16 // Process the node based on its state17 if (state === 1) {18 // Preorder: Add node data19 pre.push(node.data);20 // Change state to 2 (inorder) for this node21 stack.push([node, 2]);22 23 // Push left child onto the stack for processing24 if (node.left !== null) {25 stack.push([node.left, 1]);26 }27 } else if (state === 2) {28 // Inorder: Add node data29 inOrder.push(node.data);30 // Change state to 3 (postorder) for this node31 stack.push([node, 3]);32 33 // Push right child onto the stack for processing34 if (node.right !== null) {35 stack.push([node.right, 1]);36 }37 } else {38 // Postorder: Add node data39 post.push(node.data);40 }41 }42 43 return [inOrder, pre, post];44 }45}