
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> view; //save the result
        queue<pair<TreeNode *, int>> Q;
        if (root)
            Q.push(make_pair(root, 0)); //root and its level 0
        while (!Q.empty())
        {
            TreeNode *node = Q.front().first; //current node
            int depth = Q.front().second;     //level of the node
            Q.pop();
            if (view.size() == depth) //每行第一个
                view.push_back(node->val);
            else
                view[depth] = node->val; //每行只存一个，不断更新
            if (node->left)
                Q.push(make_pair(node->left, depth + 1));
            if (node->right)
                Q.push(make_pair(node->right, depth + 1));
        }
        return view;
    }
};
