【二叉树】Leetcode 199. 二叉树的右视图

 力扣题目链接

解题思路

        一开始,我以为只需要依次遍历最右边一列所有数即可,写出来的代码也通过了样例:

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) 
	{
		vector<int> ans;
		TreeNode* temp = root;
		while(temp != nullptr)
		{
			if(temp->right != nullptr)
			{
				temp = temp->right;
				ans.push_back(temp->val);
			}
			else
			{
				temp = temp->left;
				if(temp != nullptr)
					ans.push_back(temp->val);
			}
		}
		return ans;
    }
};

但是在提交后很明显有数据无法通过,如这组:                                   

输入:root =[1,2,3,4]                       

输出:[1,3]                                       

预期结果:[1,3,4]                                                                                         

也就是说,只要最右边的数列不是最长的一条,就一定会出现错误,因此这里需要用到二叉树的层序遍历,模板如下:

class Solution {
public:
	vector<vector<int> > levelOrder(TreeNode* root)
	{
		vector<vector<int> > ans;
		queue<TreeNode*> temp;
		
		if(root != nullptr)
			temp.push(root);
		else
			return ans;
		while(!temp.empty())
		{
			int num = temp.size();
			vector<int> layer;
			for(int i = 0; i < num; i++)
			{
				TreeNode* top = temp.front();
				temp.pop();
				layer.push_back(top->val);
				if(top->left != nullptr)
					temp.push(top->left);
				if(top->right != nullptr)
					temp.push(top->right);
			}
			ans.push_back(layer);
		}
		return ans;
	}
};

注意到只需要对输入输出稍加改动即可,也就是将每一层的数组的末项输出(因为层序遍历先从左边开始)即可。注意不要输出ans.end(),这个指向无效地址,应当输出ans.back();

完整代码

class Solution {
public:
	vector<int> rightSideView(TreeNode* root)
	{
		vector<int> ans;
		queue<TreeNode*> temp;
		
		if(root != nullptr)
			temp.push(root);
		else
			return ans;
		while(!temp.empty())
		{
			int num = temp.size();
			vector<int> layer;
			for(int i = 0; i < num; i++)
			{
				TreeNode* top = temp.front(); // 堆栈顶部元素是top,队列是front
				temp.pop();
				layer.push_back(top->val);
				if(top->left != nullptr)
					temp.push(top->left);
				if(top->right != nullptr)
					temp.push(top->right);
			}
			ans.push_back(layer.back());
		}
		return ans;
	}
};

  • 23
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Andy_Xie007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值