题目
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
解题思路
比较普通的层序遍历,只需要将先右边入队,然后每次出队整层,每次取每一层的第一个,也就是队头。
代码(C++)
/**
* 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) {
if(root==NULL) return {};
queue<TreeNode*> q;
q.push(root);
vector<int> res;
while(!q.empty()){
int qsz=q.size();
res.push_back(q.front()->val);
for(int i=0;i<qsz;++i){
TreeNode* tmp=q.front();
q.pop();
if(tmp->right) q.push(tmp->right);
if(tmp->left) q.push(tmp->left);
}
}
return res;
}
};
508



被折叠的 条评论
为什么被折叠?



