LeetCode Question: 987. Vertical Order Traversal of a Binary Tree (Level : Hard)
Note:- Scroll horizontally to see the full line of code.
/**
* 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:
map<int, map<int, vector<int>>> m;
void addToMap(TreeNode *root, int y, int x)
{
if (m.find(y) == m.end())
{
map<int, vector<int>> temp;
temp.insert(pair<int, vector<int>>(x, {root->val}));
m.insert(pair<int, map<int, vector<int>>>(y, temp));
}
else
{
if (m[y].find(x) == m[y].end())
{
m[y].insert(pair<int, vector<int>>(x, {root->val}));
}
else
{
m[y][x].push_back(root->val);
}
}
if (root->left)
{
addToMap(root->left, y - 1, x + 1);
}
if (root->right)
{
addToMap(root->right, y + 1, x + 1);
}
}
vector<vector<int>> verticalTraversal(TreeNode *root)
{
if (root)
{
addToMap(root, 0, 0);
}
vector<vector<int>> ans;
for (auto i : m)
{
vector<int> row;
for (auto j : i.second)
{
sort(j.second.begin(), j.second.end());
row.insert(row.end(), j.second.begin(), j.second.end());
}
ans.push_back(row);
}
return ans;
}
};
Comments
Post a Comment