中序遍历把每一层的最后一个放进去
代码:
/**
* 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:
queue<TreeNode*> q;
vector<int> res;
vector<int> rightSideView(TreeNode* root) {
//中序遍历把每一层的最后一个放进去
if(!root ) return res;
if(!root->left && !root->right) return {root->val};
q.push(root);
while(q.size()){
int len = q.size();
while(len--){
auto root = q.front();
q.pop();
if(root->left) q.push(root->left);
if(root->right) q.push(root->right);
if(len == 0) res.push_back(root->val);
}
}
return res;
}
};
评论区