My simple c++ solution, using level traversal and marker node


  • 0
    W

    I learned this method from someone's solution in the Binary Tree Level Order Traversal

    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> res;
            if (root == NULL) {
                return res;
            }
            queue<TreeNode *> q;
            q.push(root);
            q.push(NULL);
            while(!q.empty()) {
                TreeNode *temp = q.front();
                q.pop();
                if (temp->left) {
                    q.push(temp->left);
                }
                if (temp->right) {
                    q.push(temp->right);
                }
                if (!q.front()) {       // if see a marker, means that this level have ended
                    q.pop();
                    if (!q.empty()) {
                        q.push(NULL);
                    }
                    res.push_back(temp->val);
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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