要求:每层最右的节点
思路:
法一:dfs从右访问,第一个访问的就是
/**
* 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) {
vector<int> res;
helper(root,0,res);
return res;
}
void helper(TreeNode* root,int level,vector<int>& res){
if(!root) return;
if(res.size()==level) res.push_back(root->val);
helper(root->right,level+1,res);
helper(root->left,level+1,res);
}
};
法二:bfs
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
res.push_back(q.back()->val);
int size=q.size();
for(int i=0;i<size;++i){
TreeNode* t=q.front(); q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return res;
}
};