Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务活动详情
一、题目描述
给定一棵二叉树,求这个二叉树从左往右看过去能看到哪些节点?
二、思路分析
这个问题很有意思,其实很简单,从右往左看过去,也就是说如果我们每次优先遍历右儿子,那么每一层中最右边的那个点就一定会先被遍历到,所以我们就可以跑一边深搜,优先遍历右儿子就行了。
三、AC代码
class Solution {
public:
int ans[100];
int now=0,maxx=0;
void dfs(TreeNode* root){
if (root == NULL) {
maxx = -1;
return;
}
if (root->left!=NULL) {
now++;
dfs(root->left);
now--;
}
if (root->right!=NULL) {
now++;
dfs(root->right);
now--;
}
ans[now] = root->val;
maxx = max(maxx, now);
return;
}
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
dfs(root);
for (int i=0; i<=maxx; i++) result.push_back(ans[i]);
return result;
}
};
四、总结
但是写的时候遇到了个坑,运行时错误,说是我使用了空指针的值,但是我明明做了判断了。后来才发现,如果数据一进来就是空数组的话,就会有bug,所以得再多加一层判断一进来会不会就是空的。