Sharing my neat C++ code


  • 0
    B

    This is essentially to traverse the tree in preorder with right child first.

    class Solution {
    public:
        void rpreorder(TreeNode *node, vector<int>& ret, int level) {
            if(!node) return;
            if(level>ret.size()) ret.push_back(node->val);
            rpreorder(node->right, ret, level+1);
            rpreorder(node->left, ret, level+1);
            return;
        }
        vector<int> rightSideView(TreeNode* root) {
            vector<int> ret;
            int level = 1;
            rpreorder(root, ret, level);
            return ret;
        }
    };
    

Log in to reply
 

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