Data Structures & AlgorithmsHardAmazon/Microsoft SDE pattern
A binary tree has preorder traversal [72, 40, 18, 19, 54, 47, 92, 81] and inorder traversal [18, 19, 40, 47, 54, 72, 81, 92]. Reconstructing the tree (root = first preorder element, split inorder around it), what is its postorder traversal?
- A. 19, 18, 47, 54, 40, 81, 92, 72
- B. 18, 19, 40, 47, 54, 72, 81, 92
- C. 72, 40, 18, 19, 54, 47, 92, 81
- D. 81, 92, 47, 54, 19, 18, 40, 72
Correct answer: A. 19, 18, 47, 54, 40, 81, 92, 72
The first preorder element is the root; its position in the inorder list splits the remaining elements into left and right subtrees, applied recursively. Rebuilding the tree this way and walking it left-right-root gives postorder [19, 18, 47, 54, 40, 81, 92, 72]. Simply reversing the preorder list, [81, 92, 47, 54, 19, 18, 40, 72], only coincidentally matches postorder for some trees, not in general.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Build a binary min-heap in place from the array [37, 10, 58, 45, 19, 47, 86, 41] using bottom-up heapify (sift-down from the last internal…
- Build a binary min-heap in place from the array [34, 57, 50, 49, 69, 76, 15, 74] using bottom-up heapify (sift-down from the last internal…
- A disjoint-set (union-find with union by rank and path compression) over 9 elements (0 to 8), each initially its own component, runs this…
- An undirected graph has adjacency lists A:BCDG B:AEF C:A D:AE E:BD F:B G:A. Neighbours are always explored in alphabetical order. Which is…
- Edges A-E, D-E, B-E, A-C, A-B are added one by one to an initially empty graph on vertices {A, B, C, D, E}, using Union-Find (with path…
- In the undirected graph with edges A–B:14, B–C:2, A–D:11, D–E:8, A–F:14, B–G:11, A–G:3, what is the shortest-path distance from A to B?