-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path199.cpp
More file actions
67 lines (62 loc) · 1.8 KB
/
199.cpp
File metadata and controls
67 lines (62 loc) · 1.8 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
__________________________________________________________________________________________________
sample 4 ms submission
/**
* 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> res;
if (root == NULL) return res;
util(root, res, 1);
return res;
}
void util(TreeNode *root, vector<int> &res, int level) {
if (root == NULL) return ;
if (level == res.size() + 1) res.push_back(root->val);
util(root->right, res, level + 1);
util(root->left, res, level + 1);
}
};
__________________________________________________________________________________________________
sample 9272 kb submission
/**
* 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) {
int height = maxDepth(root);
vector<int> view(height);
dfs(root, 0, view);
return view;
}
private:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
void dfs(TreeNode* root, int level, vector<int>& view) {
if (root == nullptr) {
return;
}
view[level] = root->val;
dfs(root->left, level + 1, view);
dfs(root->right, level + 1, view);
}
};
__________________________________________________________________________________________________