-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathbinary-tree-right-side-view.cc
More file actions
48 lines (45 loc) · 931 Bytes
/
binary-tree-right-side-view.cc
File metadata and controls
48 lines (45 loc) · 931 Bytes
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
// Binary Tree Right Side View
// pre-order
class Solution {
public:
vector<int> rightSideView(TreeNode *x) {
vector<int> r;
stack<pair<TreeNode *, int>> s;
int ml = 0, l = 0;
for(;;) {
while (x) {
if (l == ml)
r.push_back(x->val), ml++;
if (x->left)
s.push(make_pair(x->left, l+1));
x = x->right;
l++;
}
if (s.empty()) break;
x = s.top().first;
l = s.top().second;
s.pop();
}
return r;
}
};
// level-order
class Solution {
public:
vector<int> rightSideView(TreeNode *x) {
vector<int> r;
if (! x) return r;
queue<TreeNode *> q;
q.push(x);
while (! q.empty()) {
r.push_back(q.back()->val);
for (size_t i = q.size(); i; i--) {
x = q.front();
q.pop();
if (x->left) q.push(x->left);
if (x->right) q.push(x->right);
}
}
return r;
}
};