Leetcode 199. 二叉树的右视图

/**
 * 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) {
        if(root==NULL)
            return vector<int>();
        vector<int> ret;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            ret.push_back(q.back()->val);
            for(int i=0; i<size; ++i)
            {
                auto tmp = q.front();
                q.pop();
                if(tmp->left)
                {
                    q.push(tmp->left);
                }
                if(tmp->right)
                {
                    q.push(tmp->right);
                }
            }
        }
        return ret;   
    }
};

猜你喜欢

转载自www.cnblogs.com/randyniu/p/9349466.html