The basic idea to attach each node a col number. When goes to node->left. col -1, goes to right, col + 1. It will make things easier using a hashmap to store the nodes and correpsonding col number.
1: first method, using hashmap. It is easy to resolve.
2. Sometimes, we just want the order but not to store the data.
/*
Vertical order traversal of binary tree.
Since, we just need to print the order out, hashmap way is not necessary.
*/
// Since we dont need to store the data. it is good for traversal then.
/*
Struct TreeNode {
int val;
TreeNode* right;
TreeNode* left;
};
*/
void findRange(TreeNode* root, int& leftRange, int& rightRange, int dep) {
if(!root) return;
if(dep < leftRange) leftRange = dep;
if(dep > rightRange) rightRange = dep;
findRange(root->left, leftRange, rightRange, dep - 1);
findRange(root->right, leftRange, rightRange, dep + 1);
}
void verticalOrder(TreeNode* root, int dep, int range) {
if(!root) return;
if(dep == range) cout << root->val << " ";
verticalOrder(root->left, dep - 1, range);
verticalOrder(root->right, dep + 1, range);
}
// Time Complexity is O(MN), M is the width of Binary Tree. N is the number of nodes in binary tree.
// Space complexity??? how to calculate.... ????
void verticalOrder(TreeNode* root) {
int minRange = 0, maxRange = 0;
findRange(root, minRange, maxRange, 0);
for(int line_no = minRange; line_no <= maxRange; ++line_no) {
verticalOrder(root, dep, line_no);
cout << endl;
}
}