Problem
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
1 <---
/ \
2 3 <---
\ \
5 4 <---
return [1, 3, 4].
Algorithm
整理一下题意:给定一棵树,假定你站在树的右边向左看,要求返回看到的结果。
问题等价于返回树的每一层最右边的节点值。由于与层次相关,故使用BFS。
按层次遍历的方法不断将节点加入到vector中。每次循环得到某一层的所有节点,由于每层最右的节点为所求节点,于是此时队列最末项即为所求值。
//BFS
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
queue<TreeNode*> q;
vector<int> view;
if(root==NULL) return view;
q.push(root);
while(!q.empty()){
view.push_back(q.back()->val);
int size=q.size();
for(int i=0;i<size;i++){
TreeNode* p=q.front();
q.pop();
if(p->left!=NULL)q.push(p->left);
if(p->right!=NULL) q.push(p->right);
}
}
return view;
}
vector中子节点的加入与父节点的删除是同步的,从而每次for循环后q队列中只包含某一层的节点。
注意for循环中循环次数用size表示,不可使用q.size()。原因是在for循环中队列的项不断更新,q的长度一直在改变,q.size()也一直在改变。而实际需要的size应该是上一层的节点数,因此用变量size=q.size()存储下来作为循环的次数。