您的位置:首页 > 其它

LeetCode "Binary Tree Vertical Order"

2015-12-15 12:26 399 查看
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, 0));
}
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 - 1));
}
if (tmp->right)
{
q.push(Rec(tmp->right, l + 1));
}
}

vector<vector<int>> ret;
for (int i = minl; i <= maxl; i++)
{
if (hm[i].size() == 0) continue;
ret.push_back(hm[i]);
}

return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: