使用递归解决这道题目。
需要注意的点: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;
}
};
这篇博客介绍了如何使用递归算法解决二叉树的右视图问题。作者强调了在递归过程中要先处理右子树,再处理左子树,以确保正确获取每个层级最右边节点的值。同时,注意防止左子树深度超过右子树,以保持视图的平衡。代码中展示了如何实现这个功能,并提供了具体的`dfs`函数和`rightSideView`函数。
1129

被折叠的 条评论
为什么被折叠?



