题意:假如你在一棵二叉树的右边,往左看,能看到哪些元素。
题解:广搜,每一层的最右边元素即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct Node
{
TreeNode* node;
int num;
Node(){}
Node(TreeNode* node,int num)
{
this->node = node;
this->num = num;
}
};
class Solution {
public:
vector<int> ans;
vector<int> rightSideView(TreeNode* root) {
if(root==NULL)
return ans;
queue<Node> q;
q.push(Node(root,0));
int num = 0;
while(!q.empty())
{
Node term = q.front();
q.pop();
if(q.empty()||q.front().num != term.num)
{
ans.push_back(term.node->val);
}
if(term.node->left!=NULL)
q.push(Node(term.node->left,term.num+1));
if(term.node->right!=NULL)
q.push(Node(term.node->right,term.num+1));
}
return ans;
}
};