题目:
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 <---
分析:
这个题目刚开始想的很简单,直接一只右子树下去,但是发现ac不过,因为题意是让我们站在右边视角,然后记录下从上到下的值,也就是,如果一棵树如果只有两个节点,并且第二个节点是根节点的左孩子,那它也是在这个数组里的,所以不可以单纯一直向右边遍历,我们需要做的就是利用广度优先搜索遍历的方法,记录每一行的节点,最后进入数组的是每一行的最后一个节点。
代码实现:
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> v;
queue<TreeNode*> q;
if(root == NULL)
return v;
q.push(root);
TreeNode* pf;
while(!q.empty())
{
int size = q.size();
while (size--)
{
pf = q.front();
q.pop();
if (pf->left)
q.push(pf->left);
if (pf->right)
q.push(pf->right);
}
v.push_back(pf->val);
}
return v;
}
};