原题地址:https://leetcode-cn.com/problems/binary-tree-right-side-view/description/
题目描述:
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 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) {
queue<TreeNode *> q1, q2;
vector<int> ans;
if(!root)
return ans;
q1.push(root);
while(!q1.empty() || !q2.empty()){
if(!q1.empty()){
ans.push_back(q1.front()->val);
while(!q1.empty()){
TreeNode* tmp = q1.front();
q1.pop();
if(tmp->right)
q2.push(tmp->right);
if(tmp->left)
q2.push(tmp->left);
}
}
else{
ans.push_back(q2.front()->val);
while(!q2.empty()){
TreeNode* tmp = q2.front();
q2.pop();
if(tmp->right)
q1.push(tmp->right);
if(tmp->left)
q1.push(tmp->left);
}
}
}
return ans;
}
};