Right view of binary tree by Recursion.
class Solution
{
public:
void treeHelper(TreeNode *root, map<int, int> &mp, int &mx_lvl, int cur_lvl)
{
if (root == NULL)
return;
if (mx_lvl < cur_lvl)
{
mx_lvl = cur_lvl;
mp[mx_lvl] = root->val;
}
treeHelper(root->right, mp, mx_lvl, cur_lvl + 1);
treeHelper(root->left, mp, mx_lvl, cur_lvl + 1);
}
vector<int> rightSideView(TreeNode *root)
{
map<int, int> ans;
int mx_lvl = -1;
treeHelper(root, ans, mx_lvl, 0);
vector<int> final;
for (auto it : ans)
final.push_back(it.second);
return final;
}
};
Comments
Post a Comment