LeetCode 199. 二叉树的右视图 C++ 用时超100%

/**
 * 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;
        queue<pair<TreeNode* ,int> > Q;
        if(root) Q.push(pair(root,0));
        while(!Q.empty()){
            TreeNode* node = Q.front().first;
            int depth = Q.front().second;
            Q.pop();
            if(result.size() == depth) result.push_back(node->val);
            else result[depth] = node->val;
            if(node->left) Q.push(pair(node->left,depth + 1));
            if(node->right) Q.push(pair(node->right,depth + 1));
        }
        
        
        
        return result;
    }
};

你可能感兴趣的:(LeetCode)