Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf64cd98

Browse files
199. Binary Tree Right Side View.cpp
1 parent2620bc4 commitf64cd98

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
classSolution {
13+
public:
14+
vector<int>rightSideView(TreeNode* root) {
15+
if(root ==NULL)return {};
16+
vector<int> ans;
17+
ans.push_back(root -> val);
18+
queue<pair<TreeNode*,int>> q;
19+
q.push({root,1});
20+
map<int,int> m;
21+
while(!q.empty()){
22+
int lvl = q.front().second;
23+
TreeNode* tempr = q.front().first -> right;
24+
TreeNode* templ = q.front().first -> left;
25+
q.pop();
26+
if(tempr ==NULLand templ ==NULL)continue;
27+
if(tempr !=NULL){
28+
q.push({tempr,lvl+1});
29+
}
30+
if(templ !=NULL){
31+
q.push({templ,lvl+1});
32+
}
33+
if(tempr !=NULLand m[lvl] ==0) ans.push_back(tempr -> val),m[lvl]=1;
34+
elseif(m[lvl] ==0)ans.push_back(templ -> val),m[lvl]=1;
35+
}
36+
return ans;
37+
}
38+
};
39+
40+
*****************
41+
42+
classSolution {
43+
public:
44+
vector<int>rightSideView(TreeNode* root) {
45+
vector<int> res;
46+
if(!root)return res;
47+
queue<TreeNode*> q;
48+
q.push(root);
49+
while(!q.empty()) {
50+
int len = q.size();
51+
while(len--) {
52+
TreeNode* curr = q.front(); q.pop();
53+
if(len ==0) res.push_back(curr->val);
54+
if(curr->left) q.push(curr->left);
55+
if(curr->right) q.push(curr->right);
56+
}
57+
}
58+
return res;
59+
}
60+
};
61+
62+
*******************
63+
64+
classSolution {
65+
public:
66+
vector v;
67+
68+
voidfun(TreeNode* root,int level,int* maxlevel)
69+
{
70+
if(root==NULL)
71+
return;
72+
if(*maxlevel<level)
73+
{
74+
v.push_back(root->val);
75+
*maxlevel=level;
76+
}
77+
fun(root->right,level+1,maxlevel);
78+
fun(root->left,level+1,maxlevel);
79+
}
80+
81+
vector<int>rightSideView(TreeNode* root) {
82+
83+
int maxlevel=0;
84+
v.clear();
85+
fun(root,1,&maxlevel);
86+
return v;
87+
}
88+
};
89+
90+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp