-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeRightSideView.cpp
More file actions
executable file
·73 lines (61 loc) · 1.64 KB
/
BinaryTreeRightSideView.cpp
File metadata and controls
executable file
·73 lines (61 loc) · 1.64 KB
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
//
// BinaryTreeRightSideView.cpp
// leetcode
//
// Created by witwolf on 5/4/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <vector>
#include <utility>
#include <deque>
#include <iostream>
using namespace std;
/**
* 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 {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
if(root == NULL){
return result;
}
deque<pair<TreeNode*,int> > nodes(1,make_pair(root, 1));
vector<int> levels(1,1);
while(!nodes.empty()){
pair<TreeNode*,int> p = nodes.front();
nodes.pop_front();
TreeNode* node = p.first;
int level = p.second;
if(!(--levels[level-1] )){
result.push_back(node->val);
}
if(levels.size() < level + 1){
levels.push_back(0);
}
if(node->left){
nodes.push_back(make_pair(node->left, level+1));
levels[level] ++ ;
}
if(node->right){
nodes.push_back(make_pair(node->right, level+1));
levels[level] ++ ;
}
}
return result;
}
};
int main(int argc,char **argv){
TreeNode node1(1),node2(2),node3(3);
node1.left = &node2;
node1.right = &node3;
Solution s;
vector<int> r = s.rightSideView(&node1);
copy(r.begin(),r.end(),ostream_iterator<int>(cout," "));
}