My c++ solution (11ms) - modified level visit with two queues


  • 0
    D
    /**
     * Definition for binary tree
     * 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> rst;
            queue<TreeNode *> pre;
            if(NULL != root) pre.push(root) ;
            while(!pre.empty()){
                rst.push_back(pre.front()->val);
                queue<TreeNode *> cur;
                while(!pre.empty()){
                    TreeNode * node = pre.front();
                    pre.pop();
                    if(NULL != node->right) cur.push(node->right);
                    if(NULL != node->left)  cur.push(node->left);
                }
                pre.swap(cur);
            }
            return rst;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.