使用队列进行层序遍历的同时,将每层的最后一个节点放入结果数组中即可。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if (root == nullptr) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
int size = q.size();
while (size -- )
{
TreeNode* t = q.front();
q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
if (size == 0) res.push_back(t->val); //判断该节点是否是该层最后一个节点
}
}
return res;
}
};