Binary Tree Vertical Order Traversal
Link
Description
Given the root
of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Example 1:
- Input:
root = [3,9,20,null,null,15,7]
- Output:
[[9],[3,15],[20],[7]]
Example 2:
- Input:
root = [3,9,8,4,0,1,7]
- Output:
[[4],[9],[3,0,1],[8],[7]]
Example 3:
- Input:
root = [3,9,8,4,0,1,7,null,null,null,2,5]
- Output:
[[4],[9,5],[3,0,1],[8,2],[7]]
Constraints:
- The number of nodes in the tree is in the range
[0, 100]
.
-100 <= Node.val <= 100
Solution
BFS
| /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
map<int, vector<int>> columnTable;
queue<pair<TreeNode*, int>> que;
que.emplace(root, 0);
while (!que.empty()) {
auto p = que.front();
que.pop();
columnTable[p.second].emplace_back(p.first->val);
if (p.first->left) que.emplace(p.first->left, p.second - 1);
if (p.first->right) que.emplace(p.first->right, p.second + 1);
}
for (auto& col : columnTable) {
res.emplace_back(col.second);
}
return res;
}
};
|
- Time complexity: \(O(N\log N)\);
- Space complexity: \(O(N)\).
Optimized BFS
| /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
unordered_map<int, vector<int>> columnTable;
queue<pair<TreeNode*, int>> que;
que.emplace(root, 0);
int minColumn = 0, maxColumn = 0;
while (!que.empty()) {
auto p = que.front();
que.pop();
int column = p.second;
if (columnTable.find(column) == columnTable.end()) {
columnTable[column] = vector<int>();
}
columnTable[column].emplace_back(p.first->val);
minColumn = min(minColumn, column);
maxColumn = max(maxColumn, column);
if (p.first->left) que.emplace(p.first->left, column - 1);
if (p.first->right) que.emplace(p.first->right, column + 1);
}
for (int i = minColumn; i <= maxColumn; i++) {
res.emplace_back(columnTable[i]);
}
return res;
}
};
|
- Time complexity: \(O(N)\);
- Space complexity: \(O(N)\).