s4553711
5/1/2017 - 7:43 AM

199-2.cpp

/**
 * 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:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> result;
        if (root == NULL) return result;
        queue<TreeNode*> curr;
        curr.push(root);
        while(!curr.empty()) {
            int size = curr.size();
            int target = size - 1;
            int i = 0;
            for(;size > 0;  size--){
                TreeNode* c = curr.front();
                curr.pop();
                if (i == target) {
                    result.push_back(c->val);
                }
                if (c->left != NULL) {
                    curr.push(c->left);
                }
                if (c->right != NULL) {
                    curr.push(c->right);
                }
                i++;
            }
        }
        return result;
    }
};