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.
For example:
Given the following binary tree,
1 <—
/ \
2 3 <—
\ \
5 4 <—
You should return [1, 3, 4].
解题思路:可以采用层次遍历的思想,每一次返回当前层的最后一个元素即可
递归代码—想不明白
void recursion(TreeNode *root, int level, vector<int> &res)
{
if(root==NULL) return ;
if(res.size()<level)
{
//cout<<"res.size()="<<res.size()<<"level="<<level<<"val="<<root->val<<endl;
res.push_back(root->val);
}
recursion(root->right, level+1, res);
recursion(root->left, level+1, res);
}
vector<int> rightSideView(TreeNode *root) {
vector<int> res;
recursion(root, 1, res);
return res;
}
非递归代码:
vector<int> rightSideView(TreeNode* root) {
if(NULL == root)
return vector<int> ();
vector<int> result;
queue<TreeNode*> que;
que.push(root);
int curLenNode = 1;
while(!que.empty())
{
TreeNode* temp = que.front();
que.pop();
curLenNode --;
if(temp->left != NULL)
que.push(temp->left);
if(temp->right != NULL)
que.push(temp->right);
if(curLenNode == 0)
{
result.push_back(temp->val);
curLenNode = que.size();
}
}
return result;
}