题目:
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.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
题目分析:
1、根据题目要求,我们要站在树的“右侧”的角度去观察一棵树,并把观察到的结果通过一个vector<int>作为答案返回;实际上就是让我们找出二叉树每一行的最右侧结点的元素值。很明显,这道题应该用BFS算法。
2、BFS算法本身是可以通过队列实现的,我们需要做的就是在队列实现BFS的同时设置参数去找到每一行结束的结点。这里的想法是设置两个变量th(this)、ne(next)分别表示本层的节点数目和下一层的节点数目。对于每一层通过th次循环,按照BFS将本层的结点的子节点放入queue中,在循环结束时将最后一个元素(即本层最后一个元素)的值压入答案容器中。并在循环结束后重新初始化th和ne(将ne的值赋给th,ne清零)以进入下一次循环。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include<queue>
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(root == NULL)
return res;
queue<TreeNode*> Q;
Q.push(root);
int th = 1;
int ne = 0;
while(!Q.empty()){
for(int i = 0; i < th; i++){
TreeNode* Node = Q.front();
if(Node->left != NULL){
Q.push(Node->left);
ne++;
}
if(Node->right != NULL){
Q.push(Node->right);
ne++;
}
if(i == th - 1){
res.push_back(Node->val);
}
Q.pop();
}
th = ne;
ne = 0;
}
return res;
}
};