Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
题目链接:https://leetcode.com/problems/binary-tree-right-side-view/
思路:后来想能不能优化,直接从右子树搜索,发现不行,看个例子
/**
* 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:
void fun(queue<TreeNode*>que,vector<int>&res)
{
int n=que.size();
int c=0;
while(c<n)
{
c++;
TreeNode *tmp=que.front();
if(c==n)
res.emplace_back(tmp->val);
if(tmp->left)
que.push(tmp->left);
if(tmp->right)
que.push(tmp->right);
que.pop();
}
if(que.size()>0)
fun(que,res);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
queue<TreeNode*> que;
if(root==NULL)
return res;
que.push(root);
fun(que,res);
return res;
}
};