-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path199_Binary Tree Right Side View.cpp
57 lines (48 loc) · 1.32 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
/**
* 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> ans;
queue<TreeNode*> tmp;
if ( root )
tmp.push(root);
while ( !tmp.empty() ) {
int size = tmp.size();
for ( int i = 1; i <= size; i++ ) {
TreeNode* node = tmp.front();
if ( i == size )
ans.push_back(node->val);
if ( node->left )
tmp.push(node->left);
if ( node->right )
tmp.push(node->right);
tmp.pop();
}
}
return ans;
}
};
// refer to discussion on LeetCode
class Solution {
public:
void recursion(TreeNode *root, int level, vector<int> &res)
{
if(root==NULL) return ;
if(res.size()<level) res.push_back(root->val);
recursion(root->right, level+1, res);
recursion(root->left, level+1, res);
}
vector<int> rightSideView(TreeNode *root) {
vector<int> res;
recursion(root, 1, res);
return res;
}
};