@@ -306,4 +306,169 @@ function verticalTraversal(root: TreeNode | null): number[][] {
306306
307307<!-- solution: end -->
308308
309+ <!-- solution: start -->
310+
311+ ### Solution 2:BFS + Sorting
312+
313+ We perform a breadth-first search (BFS) on the tree.
314+
315+ Since our final answer must be returned from leftmost column to rightmost column, we maintain:
316+ - ` leftmostCol ` : smallest column index currently stored.
317+ - ` rightmostCol ` : largest column index currently stored.
318+
319+ We also use a deque ` columnsValues ` , where each element represents
320+ a column and stores all node values belonging to that column.
321+
322+ When a newly visited node belongs to a column outside the current range:
323+
324+ - If its column index $<$ ` leftmostCol ` , we put a new column container at the front of deque.
325+ - If its column index $>$ ` rightmostCol ` , we append a new column container to the back of deque.
326+
327+ - For any column index ` col ` , its corresponding position in ` columnsValues ` can be computed as:
328+ -
329+ $$
330+ col - `leftmostCol`
331+ $$
332+
333+ This allows us to locate target column in constant time.
334+
335+ After BFS finishes, each column contains all node values belonging to that column.
336+
337+ Since BFS already visits nodes level by level, we only need to sort values within each column
338+ in ascending order to satisfy ordering requirements of the problem.
339+
340+ Finally, we output all columns from left to right.
341+
342+ #### Complexity Analysis
343+
344+ Assume binary tree contains $n$ nodes.
345+
346+ - Time Complexity: $O(n \log n)$
347+
348+ BFS visits every node exactly once, which takes $O(n)$ time. Sorting values is $O(n \log n)$ time in worst case.
349+ Therefore, overall time complexity is $O(n \log n)$.
350+
351+ - Space Complexity: $O(n)$
352+
353+ BFS queue, deque structure, and result container may collectively store all nodes, resulting in $O(n)$ space.
354+
355+ <!-- tabs: start -->
356+
357+ #### Python3
358+
359+ ``` python
360+ # Definition for a binary tree node.
361+ # class TreeNode:
362+ # def __init__(self, val=0, left=None, right=None):
363+ # self.val = val
364+ # self.left = left
365+ # self.right = right
366+ class Solution :
367+ def verticalTraversal (self , root : Optional[TreeNode]) -> list[list[int ]]:
368+ # Format: (tree node, row, column).
369+ queue: deque[tuple[TreeNode, int , int ]] = deque([(root, 0 , 0 )])
370+
371+ # Deque append left speeds up indexing.
372+ # Each tuple format: (row, value).
373+ columns_values: deque[list[tuple[int , int ]]] = deque([[]])
374+
375+ leftmost_col, rightmost_col = 0 , 0
376+
377+ while queue:
378+ node, row, column = queue.popleft()
379+
380+ if column < leftmost_col:
381+ leftmost_col = column
382+ columns_values.appendleft([])
383+
384+ if column > rightmost_col:
385+ rightmost_col = column
386+ columns_values.append([])
387+
388+ columns_values[column - leftmost_col].append((row, node.val))
389+
390+ if node.left:
391+ queue.append((node.left, row + 1 , column - 1 ))
392+ if node.right:
393+ queue.append((node.right, row + 1 , column + 1 ))
394+
395+ vertical_traversal: list[list[int ]] = []
396+
397+ for column_values in columns_values:
398+ vertical_traversal.append([])
399+
400+ column_values.sort()
401+ for _, value in column_values:
402+ vertical_traversal[- 1 ].append(value)
403+
404+ return vertical_traversal
405+ ```
406+
407+ #### C++
408+
409+ ``` cpp
410+ /* *
411+ * Definition for a binary tree node.
412+ * struct TreeNode {
413+ * int val;
414+ * TreeNode *left;
415+ * TreeNode *right;
416+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
417+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
418+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
419+ * };
420+ */
421+ class Solution {
422+ public:
423+ vector<vector<int >> verticalTraversal(TreeNode* root) {
424+ // Each tuple format: {tree node, row, column}.
425+ deque<tuple<TreeNode* , int, int>> queue = {{root, 0, 0}};
426+
427+ // Each tuple format: {row, value}.
428+ deque<vector<tuple<int, int>>> columnsValues = {{}};
429+
430+ int leftmostCol = 0, rightmostCol = 0;
431+
432+ while (!queue.empty()) {
433+ auto [node, row, column] = queue.front();
434+ queue.pop_front();
435+
436+ if (column < leftmostCol) {
437+ leftmostCol = column;
438+ columnsValues.push_front({});
439+ }
440+
441+ if (column > rightmostCol) {
442+ rightmostCol = column;
443+ columnsValues.push_back({});
444+ }
445+
446+ columnsValues[column - leftmostCol].push_back({row, node->val});
447+
448+ if (node->left != nullptr)
449+ queue.push_back({node->left, row + 1, column - 1});
450+
451+ if (node->right != nullptr)
452+ queue.push_back({node->right, row + 1, column + 1});
453+ }
454+
455+ vector<vector<int>> verticalTraversal = {};
456+
457+ for (auto columnValues : columnsValues) { // Need to sort so no const.
458+ verticalTraversal.push_back({});
459+
460+ sort (columnValues.begin(), columnValues.end());
461+ for (const auto& [ row, value] : columnValues)
462+ verticalTraversal.back().push_back(value);
463+ }
464+
465+ return verticalTraversal;
466+ }
467+ };
468+ ```
469+
470+ <!-- tabs: end -->
471+
472+ <!-- solution: end -->
473+
309474<!-- problem: end -->
0 commit comments