30 Day Challenge Day 4 | Hackrank - Tree : Top View
题解
俯视角度下观察结果,我想到用root作为基准,令其序号为0,相应的,左节点在根节点基础上序号减一,而右节点加一。
用一个队列,自上而下逐层遍历。因为观察角度是从上往下,上层的节点会遮住同一列的下层所有节点。一边往下,一遍往左右两侧探索,遇到水平方向更远的节点都要保存到结果中。
void topView(Node * root) {
// Take root position as a base, move left -1, move right +1
if(!root) return;
vector<int> leftward, rightward;
queue<pair<Node*, int>> q;
q.push({root, 0});
while(!q.empty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
pair<Node*, int> n = q.front();
q.pop();
if(n.second < 0 && leftward.size() < abs(n.second)) {
leftward.push_back(n.first->data);
} else if(n.second > 0 && rightward.size() < abs(n.second)) {
rightward.push_back(n.first->data);
}
if(n.first->left) {
q.push({n.first->left, n.second - 1});
}
if(n.first->right) {
q.push({n.first->right, n.second + 1});
}
}
}
for(int i = leftward.size()-1; i >= 0; i--) {
cout << leftward[i] << " ";
}
cout << root->data << " ";
for(int i = 0; i < rightward.size(); i++) {
cout << rightward[i] << " ";
}
return;
}