LeetCode 199. Binary Tree Right Side View

 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         vector<int> res;
14         if(!root) return res;
15         
16         queue<TreeNode*> q1, q2;
17         q1.push(root);
18         while(!q1.empty()){
19             res.push_back(q1.back()->val);
20             while(!q1.empty()){
21                 TreeNode* cur = q1.front();
22                 q1.pop();
23                 if(cur->left) q2.push(cur->left);
24                 if(cur->right) q2.push(cur->right);
25             }
26             q1.swap(q2);
27         }
28         return res;
29     }
30 };

思路:类似于103zigzag那道题,q1存当前层的所有节点,q2存下一层所有节点(按从左往右的顺序),每次取q1.front()即当前层的最右节点。最后q1、q2进行swap。

 

在得到q2那一步的代码尤其丑,貌似有更优解,留坑。

 

posted @ 2016-03-01 21:03  co0oder  阅读(142)  评论(0编辑  收藏  举报