思路:遍历二叉树,先右后左,在第一次遍历到某一层的时候,记录该元素。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void dfs(TreeNode* ptr, int depth, vector<int>& res)
{
if (ptr == NULL)
{
return;
}
if (depth >= res.size())
{
res.push_back(ptr->val);
}
dfs(ptr->right, depth + 1, res);
dfs(ptr->left, depth + 1, res);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
dfs(root, 0, res);
return res;
}
};