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].
/**
* 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> vec;
queue<struct TreeNode*> que1;
queue<struct TreeNode*> que2;
if (root == NULL)
return vec;
struct TreeNode* temp;
que1.push(root);
while (!que1.empty() || !que2.empty()) {
if (!que1.empty()) {
while (que1.size() > 0) {
temp = que1.front();
if (que1.size() == 1)
vec.push_back(temp -> val);
if (temp -> left != NULL)
que2.push(temp -> left);
if (temp -> right != NULL)
que2.push(temp -> right);
que1.pop();
}
} else if (!que2.empty()) {
while (que2.size() > 0) {
temp = que2.front();
if (que2.size() == 1)
vec.push_back(temp -> val);
if (temp -> left != NULL)
que1.push(temp -> left);
if (temp -> right != NULL)
que1.push(temp -> right);
que2.pop();
}
}
}
return vec;
}
};
这道题目也是广度优先搜索的一个典型例子,按照题目的意思是需要输出二叉树中每一层最右边的那个节点的值,因此只需要层序遍历二叉树,将队列中每一层的最后一个元素输出出来就好了,使用这种方法只会对二叉树的每个节点访问有且只有一次,因此如果节点的数目是N的话,需要的时间复杂度是O(N).空间复杂度是O(1)级别的。
虽然这道题使用递归方法也可以做,代码长度也会比较短,但是我认为可以不使用递归实现就完成的题目最好还是不要用递归吧,递归对系统资源的消耗比较大,像这样本来不需要使用递归就可以完成的题目还是直接使用层序遍历就好,况且使用层序遍历的时间复杂度和空间复杂度都还是比较优秀的。