给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
写这道题的初衷是因为深度搜索的思路,要跳出舒适区,每一道题的收获其实是思维的扩展。
广度搜索(正常思路)
不多解释了,很简单。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> v;
if(!root) return v;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int size=q.size();
for(int i=1;i<=size;++i)
{
TreeNode* cur=q.front();
if(i==size)
v.push_back(cur->val);
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
}
return v;
}
};
深度搜索
我们要做的是改变深度搜索的思路。看了一眼官方题解根左右深搜觉得还是很死板。
1.改变深度搜索的顺序,变为根右左。这样我们能第一时间获取到最右面的节点
2.寻找找最右面的节点的判定条件:细想用深度来找,具体看代码。
class Solution {
public:
void preOrder(TreeNode* root,vector<int>& v,int curDepth,int& depth)//depth为引用
{
if(root==nullptr) return;
curDepth++;//当前节点的深度
if(curDepth==depth)
{
v.push_back(root->val);
depth++;
}
preOrder(root->right,v,curDepth,depth);
preOrder(root->left,v,curDepth,depth);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> v;
if(!root) return v;
int depth=1;//下次要预判的深度
preOrder(root,v,0,depth);
return v;
}
};