Simple C++ using depth list

  • 0

    Create a list of nodes for each depth of the tree using preorder traversal, and return the vector comprised of the last node added at each depth.

    class Solution {
        vector<int> rightSideView(TreeNode* root) {
            vector<int> result;
            vector<vector<int>> nodeListPerDepth;
            depthList(root, nodeListPerDepth, 0);
            for (auto nodeList : nodeListPerDepth){
            return result;
        void depthList(TreeNode* node, vector<vector<int>>& list, int depth){
            if (!node) { return; }
            if (list.size() == depth){
            depthList(node->left, list, depth+1);
            depthList(node->right, list, depth+1);

Log in to reply

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