Sponsored
Sponsored
This approach uses a Breadth-First Search (BFS) to traverse the tree while tracking each node's position (row, col). We use a queue to manage our BFS process, which stores tuples of (node, row, col). As we visit each node, we place it into a list corresponding to its column index. Finally, we sort each column by first row, then value, and construct the result.
Time Complexity: O(N log N) due to sorting, where N is the number of nodes.
Space Complexity: O(N) for the storage of node values, where N is the number of nodes.
1#include <iostream>
2#include <vector>
3#include <map>
4#include <deque>
5#include <algorithm>
6using namespace std;
7
8struct TreeNode {
9 int val;
10 TreeNode *left;
11 TreeNode *right;
12 TreeNode() : val(0), left(nullptr), right(nullptr) {}
13 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
14 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
15};
16
17map<int, vector<pair<int, int>>> col_table;
18
19double min_col = 0, max_col = 0;
20
21diagnostics Queue<pair<TreeNode*, pair<int, int>>> queue;
22
23queue.push_back(make_pair(root, make_pair(0, 0)));
24while (!queue.empty()) {
25 auto [node, p] = queue.front();
26 queue.pop_front();
27 int row = p.first, col = p.second;
28 col_table[col].emplace_back(row, node->val);
29 min_col = min(min_col, col);
30 max_col = max(max_col, col);
31 if (node->left) queue.push_back(make_pair(node->left, make_pair(row + 1, col - 1)));
32 if (node->right) queue.push_back(make_pair(node->right, make_pair(row + 1, col + 1)));
33}
34
35vector<vector<int>> result;
36for (int col = min_col; col <= max_col; ++col) {
37 sort(col_table[col].begin(), col_table[col].end());
38 vector<int> col_vals;
39 for (auto [row, val] : col_table[col]) {
40 col_vals.push_back(val);
41 }
42 result.push_back(col_vals);
43}
44
This solution creates a map to record node values by their column indices, tracking row positions using a deque-based BFS. Here, nodes within each column get sorted based on row and node value, with results compiled in sequence from minimum to maximum column index.
This method involves performing a pre-order traversal (DFS) to collect all nodes along with their column and row indices. Once collected, nodes are sorted based on their columns first, then their rows, and finally their values. The sorted list is then grouped into lists according to their column indices to produce the final vertical order traversal.
Time Complexity: O(N log N) due to sorting, where N is the total number of nodes.
Space Complexity: O(N) to store all the nodes along with their positions.
1def verticalOrderTraversal(root):
2 node_list
The DFS collects nodes with their positions into a list. This unsorted list is then sorted by column, row, and value. Finally, nodes are classified into their corresponding columns based on sorted order.
This approach relies on sorting all nodes at the end to define their order in the result.