4ms C++ solution, using level order traversal


  • 0
    I
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ret;
        vector<vector<TreeNode*>> q(2);
        if (!root) return ret;
        int idx = 0;
        q[idx].push_back(root);
        while (!q[idx].empty()) {
            q[1 - idx].clear();
            ret.push_back(q[idx][0]->val);
            for (int i = 0; i < q[idx].size(); i++) {
                if (q[idx][i]->right) q[1 - idx].push_back(q[idx][i]->right);
                if (q[idx][i]->left) q[1 - idx].push_back(q[idx][i]->left);
            }
            idx = 1 - idx;
        }
        return ret;
    }

Log in to reply
 

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