LeetCode "Binary Tree Vertical Order"

时间:2022-01-25 04:50:24

BFS + HashTable

class Solution
{
int maxl, minl;
unordered_map<int, vector<int>> hm;
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
maxl = INT_MIN;
minl = INT_MAX; typedef pair<TreeNode*, int> Rec;
queue<Rec> q;
if (root)
{
q.push(Rec(root, ));
}
while (!q.empty())
{
Rec curr = q.front(); q.pop();
int l = curr.second;
maxl = max(maxl, l);
minl = min(minl, l); TreeNode *tmp = curr.first;
hm[l].push_back(tmp->val); if (tmp->left)
{
q.push(Rec(tmp->left, l - ));
}
if (tmp->right)
{
q.push(Rec(tmp->right, l + ));
}
} vector<vector<int>> ret;
for (int i = minl; i <= maxl; i++)
{
if (hm[i].size() == ) continue;
ret.push_back(hm[i]);
} return ret;
}
};