C++ solution, with one queue used


  • 0
    L

    The idea is to binary tree level traversal, and at the end of each level, push a NULL to denote the end of this level.

    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
            vector<int> res;
            if (root == NULL) return res;
            queue<TreeNode*> nodes;
            nodes.push(root);
            nodes.push(NULL);
            TreeNode *prev = root;
            while (!nodes.empty()) {
                TreeNode *curr = nodes.front();
                nodes.pop();
                if (curr == NULL) {
                    res.push_back(prev->val);
                    // push a NULL when meeting a NULL, unless the nodes is empty (i.e. last level)
                    if (nodes.empty()) break;
                    else {
                        nodes.push(NULL);
                    }
                } else {
                    prev = curr;
                    if (curr->left) nodes.push(curr->left);
                    if (curr->right) nodes.push(curr->right);
                }
            }
            return res;
        }
    };

  • 0
    C

    IMHO, code will be much clearer if you use recursion and leave the stack handling to compiler. It will do a better job of optimizing as well.


Log in to reply
 

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