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]]
Example 4:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 100]
. -100 <= Node.val <= 100
Companies:
Facebook, Amazon, Bloomberg, Microsoft
Related Topics:
Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree
Similar Questions:
// OJ: https://leetcode.com/problems/binary-tree-vertical-order-traversal/
// Author: github.com/lzl124631x
// Time: O(NlogW) where N is the number of nodes in the tree and W is the width of the tree
// Space: O(N)
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
if (!root) return {};
map<int, vector<int>> m;
queue<pair<TreeNode*, int>> q;
q.emplace(root, 0);
while (q.size()) {
auto [node, index] = q.front();
q.pop();
m[index].push_back(node->val);
if (node->left) q.emplace(node->left, index - 1);
if (node->right) q.emplace(node->right, index + 1);
}
vector<vector<int>> ans;
for (auto &[index, v] : m) ans.push_back(v);
return ans;
}
};