使用递归解决这道题目。
需要注意的点:1、要先递归右子树,再递归左子树。
2、要考虑二叉树的深度,防止左子树深度大于右子树深度这种情况
class Solution {
public:
vector<int> ans;
void dfs(TreeNode* root, int depth){
if(!root) return;
if(depth == ans.size()){
ans.push_back(root->val);
}
++depth;
dfs(root->right, depth);
dfs(root->left, depth);
}
vector<int> rightSideView(TreeNode* root) {
int depth=0;
dfs(root, 0);
return ans;
}
};