原题
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <—
/ \
2 3 <—
\ \
5 4 <—
You should return [1, 3, 4].
分析
也就是每一层的最右元素,层序遍历即可。
代码
class Solution {
private:
void bfs(TreeNode*root, vector<int>&result)
{
queue<TreeNode *>s;
s.push(root);
stack<int>level;
while (!s.empty())
{
int size = s.size();
int count = 0;
while (count < size)
{
TreeNode* p = s.front();
level.push(p->val);
s.pop();
if (p->left != NULL)
{
s.push(p->left);
}
if (p->right != NULL)
{
s.push(p->right);
}
++count;
}
result.push_back(level.top());
}
}
public:
vector<int> rightSideView(TreeNode* root) {
vector<int>result;
if(root==NULL)
return result;
bfs(root, result);
return result;
}
};