【48】199. Binary Tree Right Side View
199. Binary Tree Right Side View
Description Submission Solutions Add to List
- Total Accepted: 68720
- Total Submissions: 176072
- Difficulty: Medium
- Contributors: Admin
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> rightSideView(TreeNode* root) { 13 //层序遍历,每次输出queue.back()即可。 14 vector<int> res; 15 if(!root) return res; 16 queue<TreeNode*> q; 17 q.push(root); 18 //res.push_back(root -> val); 19 while(!q.empty()){ 20 res.push_back(q.back() -> val); 21 //TreeNode* tmp = q.front(); 22 int size = q.size(); 23 //q.pop(); 24 //res.push_back(q.back() -> val); 25 //q.pop(); 26 for(int i = 0; i < size; i++){ 27 TreeNode* tmp = q.front();//在for循环里pop 28 q.pop(); 29 if(tmp -> left){ 30 q.push(tmp -> left); 31 } 32 if(tmp -> right){ 33 q.push(tmp -> right); 34 } 35 } 36 } 37 return res; 38 } 39 };