forked from shruti170901/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Right Side View.cpp
74 lines (56 loc) · 1.2 KB
/
Binary Tree Right Side View.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution
{
public:
vector<int> rightSideView(TreeNode *root)
{
vector<int> output;
if (root == nullptr)
{
return output;
}
queue<TreeNode *> q;
q.push(root);
TreeNode *curr = nullptr;
while (!q.empty())
{
int size = q.size();
int last = 0;
while (last++ < size)
{
curr = q.front();
q.pop();
if (last == size)
output.push_back(curr->val);
if (curr->left)
q.push(curr->left);
if (curr->right)
q.push(curr->right);
}
}
return output;
}
};
******************************************************************************************************************************************************
class Solution
{
public:
unordered_map<int, int> map;
void rightView(TreeNode *root, int level)
{
if (root == nullptr)
return;
map[level] = root->val;
rightView(root->left, level + 1);
rightView(root->right, level + 1);
}
vector<int> rightSideView(TreeNode *root)
{
vector<int> output;
rightView(root, 0);
for (int i = 0; i < map.size(); i++)
{
output.push_back(map[i]);
}
return output;
}
};