Share my two C++ solutions,easy to understand

• Iterative Solution:

``````class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ret;
if (root == NULL)
return ret;

queue<TreeNode *> q;
TreeNode *cur = NULL;
int curLevelNodes = 0;

q.push(root);

while (!q.empty())
{
curLevelNodes = q.size();//number of nodes in the current level

while (curLevelNodes--)
{
cur = q.front();
q.pop();
if (cur->left != NULL)
q.push(cur->left);
if (cur->right != NULL)
q.push(cur->right);
}
ret.push_back(cur->val);//the rightmost node int current level
}

return ret;
}
};``````

• Recursive Solution:

``````class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ret;
if (root == NULL)
return ret;

rightView(root, 1, ret);//assuming thar root at level 1

return ret;
}

void rightView(TreeNode* cur, int level, vector<int> &ret)
{
if (cur != NULL)
{
if (level > ret.size())//thers is no node (belong to current level) to be added into ret
ret.push_back(cur->val);

//look from right to left
rightView(cur->right, level+1, ret);
rightView(cur->left, level+1, ret);
}
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.