Binary Tree Vertical Order Traversal
Data Structure to catch the nodes
map<int, map<int, vector<int>>
1) The first int indicates the index or columns;
2) The second int indicates the index of rows;
3) The vector<int> indicates what's inside that column and that row;
code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> ret;
if(root == NULL)
{
return ret;
}
map<int, map<int, vector<int>>> hash;
traversal(root, hash, 0, 0);
for(auto& kv : hash)
{
vector<int> tmp;
for(auto& kv2 : kv.second)
{
for(int i : kv2.second)
{
tmp.push_back(i);
}
}
ret.push_back(tmp);
}
return ret;
}
void traversal(TreeNode* root, map<int, map<int, vector<int>>>& hash, int index, int level)
{
if(root == NULL)
{
return ;
}
hash[index][level].push_back(root->val);
traversal(root->left, hash, index-1, level+1);
traversal(root->right, hash, index+1, level+1);
}
};