-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary-tree-right-side-view.cpp
56 lines (49 loc) · 1.38 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
// https://leetcode.com/problems/binary-tree-right-side-view/
// Recursive Traversal - Root, right, left
class Solution {
public:
vector<int> ans;
void solve(TreeNode* node, int level){
if(!node) return;
if(level == ans.size()) ans.push_back(node -> val);
if(node -> right) solve(node -> right, level + 1);
if(node -> left) solve(node -> left, level + 1);
}
vector<int> rightSideView(TreeNode* root) {
solve(root, 0);
return ans;
}
};
// Iterative Traversal - Level Order
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector <int> v;
if (root == NULL)
return v;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
// get number of nodes for each level
int n = q.size();
// traverse all the nodes of the current level
while (n--) {
TreeNode* x = q.front();
q.pop();
// print the last node of each level
if (n == 0) {
v.push_back(x -> val);
}
// if left child is not null push it into the
// queue
if (x->left)
q.push(x->left);
// if right child is not null push it into the
// queue
if (x->right)
q.push(x->right);
}
}
return v;
}
};