该题有两种解法,深搜和广搜,深搜整体更优
广搜更加好想,保留每次循环队列最后一个节点值
class Solution {
private:
vector<int> result;
int max_index = -1;
void dfs(TreeNode* root,int startIndex)
{
if (root == nullptr) return;
if (startIndex > max_index)
{
result.push_back(root->val);
max_index = startIndex;
}
dfs(root -> right, startIndex + 1);
dfs(root -> left, startIndex + 1);
}
public:
vector<int> rightSideView(TreeNode* root) {
dfs(root,0);
return result;
}
};
深搜,根右左遍历,当depth比当前maxdepth大时更新depth并push当前节点值到结果队列
class Solution {
public:
//右子树优先遍历
int maxdepth = -1;
vector<int>ans;
vector<int> rightSideView(TreeNode* root) {
dfs(root,0);
return ans;
}
void dfs(TreeNode*root,int depth){
if(!root)return;
if(depth>maxdepth){
maxdepth = depth;
ans.push_back(root->val);
}
dfs(root->right,depth+1);
dfs(root->left,depth+1);
}
};