Implement tree traversals, BFS, and subsets generation | Microsoft
|Home/Coding & Algorithms/Microsoft
Implement tree traversals, BFS, and subsets generation
Microsoft
Sep 6, 2025, 12:00 AM
Software Engineer
Onsite
Coding & Algorithms
0
0
Define a TreeNode class for a binary tree with an integer value and left/right pointers. Implement preorder, inorder, and postorder traversals:
(a) recursive versions;
(b) iterative versions using an explicit stack (you may use two stacks for postorder). Return the traversal orders as lists and analyze time and space complexity.
Given an unweighted graph as an adjacency list and a source node s, implement BFS to return the visitation order, a distance map of minimum edge distances from s, and a parent map to reconstruct shortest paths. Handle disconnected graphs by describing how to traverse all components and produce results for each.
Given an array of distinct integers nums, generate the power set (all subsets). Provide
(a) a backtracking solution; and
(b) an iterative solution using for-loops only (no recursion), explaining how subsets are built layer by layer. Return subsets in any order and analyze complexity.