给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
通过次数31,361提交次数48,920
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
算法讲解
点击此处.
一、DFS
class Solution {
public:
vector<int> res;
vector<int> rightSideView(TreeNode* root) {
int len = 0;//层数
Dfs(root, len);
return res;
}
void Dfs(TreeNode* root, int len)
{//此处的len没有&是应为深度优先遍历是将最右值第一个读取
//当右树为空,此时需要判断左树的该层是否为空
//所以又从左树开始向下走,但是这些节点不需要进入结果
//此时需要len != res.size() 所以不用&
if(root == NULL)
{
return ;
}
//遍历规则该层的第一个为结果值
if(len == res.size())
{
res.push_back(root->val);
}
len++;
Dfs(root->right, len);
Dfs(root->left, len);
}
};
二、BFS
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
queue<TreeNode*> q;
if (root == nullptr)
{
return res;
}
q.push(root);
while (!q.empty())
{
int size = q.size();//该层的节点个数
for(int i = 0; i < size; i++)
{
TreeNode* index = q.front();
if (index->left != NULL)
{
q.push(index->left);
}
if (index->right != NULL)
{
q.push(index->right);
}
//从左往右读所以结果值为当前层的最后一个值
if(i == q.size - 1)
{
res.push_back(q.front()->val);
}
q.pop();
}
}
return res;
}
};