একটি বাইনারি ট্রি দেওয়া আছে। এর নোডগুলোর ভার্টিকাল অর্ডার ট্রাভার্সাল বের করতে হবে। একই সারি ও কলামে একাধিক নোড থাকলে বাম থেকে ডানের ক্রমে থাকবে।
উদাহরণ

আউটপুট: [[9],[3,15],[20],[7]]
সমাধানের পদ্ধতি (BFS + Column Index Mapping)
- একটি ম্যাপ
m(কলাম ইনডেক্স -> নোড ভ্যালু লিস্ট) ঘোষণা করুন। - রিকারসিভ
solve(node, x)দিয়ে কলাম ইনডেক্স অনুযায়ী নোডগুলো ম্যাপে রাখুন (বামে x-1, ডানে x+1)। - BFS ব্যবহার করে লেভেল অর্ডার ট্রাভার্সাল করুন:
- কিউতে
{column, node}পেয়ার রাখুন। - প্রতি লেভেলে সব নোড প্রসেস করুন, বাম ও ডান চাইল্ডের জন্য কলাম আপডেট করে কিউতে পুশ করুন এবং ম্যাপে যোগ করুন।
- কিউতে
- ম্যাপ থেকে সর্টেড কি অনুযায়ী রেজাল্ট ভেক্টর বানান।
- রিটার্ন করুন।
C++ কোড উদাহরণ
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int>> v) {
cout << "[";
for(int i = 0; i < v.size(); i++) {
cout << "[";
for(int j = 0; j < v[i].size(); j++)
cout << v[i][j] << ", ";
cout << "],";
}
cout << "]" << endl;
}
class TreeNode {
public:
int val;
TreeNode *left, *right;
TreeNode(int data) {
val = data;
left = right = NULL;
}
};
void insert(TreeNode **root, int val) {
queue<TreeNode*> q;
q.push(*root);
while(q.size()) {
TreeNode *temp = q.front(); q.pop();
if(!temp->left) {
if(val != NULL) temp->left = new TreeNode(val);
else temp->left = new TreeNode(0);
return;
} else q.push(temp->left);
if(!temp->right) {
if(val != NULL) temp->right = new TreeNode(val);
else temp->right = new TreeNode(0);
return;
} else q.push(temp->right);
}
}
TreeNode* make_tree(vector<int> v) {
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i < v.size(); i++)
insert(&root, v[i]);
return root;
}
class Solution {
public:
map<int, vector<int>> m;
void solve(TreeNode* node, int x = 0) {
if (!node || node->val == 0) return;
solve(node->left, x - 1);
solve(node->right, x + 1);
m[x].push_back(node->val);
}
static bool cmp(vector<int>& a, vector<int>& b) {
return a[0] != b[0] ? a[0] < b[0] : a[1] < b[1];
}
vector<vector<int>> verticalOrder(TreeNode* root) {
if (!root) return {};
queue<pair<int, TreeNode*>> q;
q.push({0, root});
m[0].push_back(root->val);
while (!q.empty()) {
int sz = q.size();
while (sz--) {
pair<int, TreeNode*> curr = q.front(); q.pop();
TreeNode* node = curr.second;
int x = curr.first;
if (node->left && node->left->val != 0) {
q.push({x - 1, node->left});
m[x - 1].push_back(node->left->val);
}
if (node->right && node->right->val != 0) {
q.push({x + 1, node->right});
m[x + 1].push_back(node->right->val);
}
}
}
vector<vector<int>> ret;
for (auto it = m.begin(); it != m.end(); it++)
ret.push_back(it->second);
return ret;
}
};
int main() {
Solution ob;
vector<int> v = {3,9,20,NULL,NULL,15,7};
TreeNode *root = make_tree(v);
print_vector(ob.verticalOrder(root));
return 0;
}
ইনপুট
{3,9,20,NULL,NULL,15,7}
আউটপুট
[[9, ],[3, 15, ],[20, ],[7, ],]