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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
Accepted
204,031
Submissions
406,980
这个题目主要应用的是树的广度优先搜索的另一种写法,普通的广度优先搜索是一个节点一个节点出队,无法完全体现出“层序”这个特征,所以这个题目很难用普通的层序遍历完成。可以创建第二个队列储存一层的信息实现真正的层序遍历。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if(root == NULL)
return ans;
queue<TreeNode*> q;
q.push(root);
while(q.size() != 0)
{
queue<TreeNode*> qt;//创建第二个队列
ans.push_back(q.back() -> val);
while(q.size() != 0)
{
TreeNode *current = q.front();
q.pop();
//储存这一层的信息
if(current -> left != NULL)
qt.push(current -> left);
if(current -> right != NULL)
qt.push(current -> right);
}
q = qt;
}
return ans;
}
};