|
| 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 | + |