-
Notifications
You must be signed in to change notification settings - Fork 0
/
199. Binary Tree Right Side View.cpp
83 lines (61 loc) · 1.83 KB
/
199. 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
75
76
77
78
79
80
81
82
83
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
void helper(TreeNode *root, vector<int> &result, int level) {
if(!root)
return;
if(result.size() < level + 1)
result.push_back(root->val);
helper(root->right, result, level + 1);
helper(root->left, result, level + 1 );
}
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
helper(root,result,0);
return result;
}
};
----------------
/*
Note to self : leveloftree needs to be passed as a pointer. Because otherwise,
leveloftree takes the value of the previous self in the recursion tree. The line
leveloftree won't take the value of curlevel unless its state is maintained through a pointer
The other alternative is to drop the variable leveloftree and use
result.size() < curlevel
*/
class Solution {
void printrightsideview(TreeNode *root, int curlevel, int *leveloftree, vector<int> &result) {
if(root == NULL)
return;
if(curlevel > *leveloftree ) {
result.push_back(root->val);
*leveloftree = curlevel;
}
printrightsideview(root->right,curlevel+1,leveloftree,result);
printrightsideview(root->left,curlevel+1,leveloftree,result);
}
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
int m = 0;
printrightsideview(root, 1, &m, result);
return result;
}
};