Easy level order traversal (select the last one of each level)


  • 0
    S
      vector<int> rightSideView(TreeNode* root) {
            vector<int> ans;
            if(root == NULL) return ans;
            queue<TreeNode *> node;
            node.push(root);
            int next_level = 0;
            int to_be_print = 1;
            while(!node.empty())
            {
                TreeNode *p = node.front();
                if(p->left)
                {
                    node.push(p->left);
                    ++next_level;
                }
                if(p->right)
                {
                    node.push(p->right);
                    ++next_level;
                }
                node.pop();
                --to_be_print;
                if(to_be_print == 0)
                {
                    ans.push_back(p->val);
                    to_be_print = next_level;
                    next_level = 0;
                }
            }
            return ans;
        }

Log in to reply
 

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