一、题目描述:199. 二叉树的右视图(中等)
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:1 <---
/ \
2 3 <---
\ \
5 4 <---来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
相当于层序遍历取最右值
方法一、
递归方法是分别遍历一个节点的右节点和左节点,因为是从右边看过来,所以我们需要首先遍历右节点。这里有个疑问,当遍历左节点时候,怎么判定它右边没有其他节点了呢?这里我们用到一个变量level,对于同一层的节点,如果res数组的大小已经等于level了,说明右边已经有节点存入数组了,该节点就不用再保存。一直递归下去就可以得到结果。
方法二、
利用队列,根元素入队,使用一个变量count记录当前层的剩下元素个数,count_next记录下一层的元素个数,进入循环,将队列头取出,将队列头左指针(非空)入队,count_next++,右指针(非空)入队,count_next++。当count == 0(说明到了这一层的最后一个元素)将其记录,并且初始化count = count_next,count_next = 0,直到队列为空
三、代码
方法一、
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
helper(root,0,res);
return res;
}
void helper(TreeNode* root,int level,vector<int>& res){
if(!root) return;
if(res.size()==level) res.push_back(root->val);
helper(root->right,level+1,res);
helper(root->left,level+1,res);
}
};
方法二、
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
deque<TreeNode * > que;
vector<int> save;
if(root == NULL)
return save;
que.push_back(root);
int count = 1;
int count_next = 0;
while(que.size() > 0)
{
if((*que.begin())->left != NULL)
{
que.push_back((*que.begin())->left);
count_next ++;
}
if((*que.begin())->right != NULL)
{
que.push_back((*que.begin())->right);
count_next ++;
}
count --;
if(count == 0)
{
save.push_back((*que.begin())->val);
count = count_next;
count_next = 0;
}
que.pop_front();
}
return save;
}
void rView(TreeNode * root,vector<int> & stack)
{
if(root == NULL)
return;
stack.push_back(root->val);
rView(root->right,stack);
if(root->right == NULL)
{
rView(root->left,stack);
}
}
};