-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Tree Right Side View
57 lines (55 loc) · 1.4 KB
/
Binary Tree Right Side View
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:
void helper(TreeNode* root,vector<int>& ans){
if(root==NULL)
return;
ans.push_back(root->val);
if(root->right!=NULL)
return helper(root->right,ans);
else if(root->left!=NULL)
return helper(root->left,ans);
else
return;
}
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if(root==NULL)
return ans;
/*helper(root,ans);
return ans;*/
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
bool pushit=true;
while(!q.empty()){
TreeNode* temp=q.front();
q.pop();
if(temp==NULL){
if(!q.empty())
q.push(NULL);
pushit=true;
}
else{
if(pushit)
ans.push_back(temp->val);
if(temp->right)
q.push(temp->right);
if(temp->left)
q.push(temp->left);
/*while(q.front()!=NULL)
q.pop();*/
pushit=false;
}
}
return ans;
}
};