求二叉树中,每层最右边的节点的值,序列化每层二叉树,然后输出每层最后一个节点即可。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans(0);
if (NULL == root)
{
return ans;
}
queue<TreeNode *> qList;
qList.push(root);
while (qList.size() > 0)
{
int size = qList.size();
for (int i = 0;i < size;i++)
{
TreeNode * head = qList.front();
if (NULL != head->left)
{
qList.push(head->left);
}
if (NULL != head->right)
{
qList.push(head->right);
}
qList.pop();
if (i == size-1)
{
ans.push_back(head->val);
}
}
}
return ans;
}
};