//给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
//
// 示例:
//
// 输入: [1,2,3,null,5,null,4]
//输出: [1, 3, 4]
//解释:
//
// 1 <---
// / \
//2 3 <---
// \ \
// 5 4 <---
//
// Related Topics 树 深度优先搜索 广度优先搜索 递归 队列
// 👍 412 👎 0
/*
* 199 二叉树的右视图
* 2021-03-01 14:17:44
* @author oxygenbytes
*/
#include "leetcode.h"
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
if(!root) return {};
queue<TreeNode*> q;
q.push(root);
vector<int> ans;
while(q.size()){
ans.push_back(q.back()->val);
int n = q.size();
for(int i = n - 1;i >= 0;i--){
auto ptr = q.front();q.pop();
if(ptr->left) q.push(ptr->left);
if(ptr->right) q.push(ptr->right);
}
}
return ans;
}
};
//leetcode submit region end(Prohibit modification and deletion)