c++ easy to understand preorder traversal method


  • 0
    Z

    just add two additional params, current_level and current_level printed or not.
    void helper(TreeNode* root, vector<int>& res, int level, int& printed_level)
    {
    if(root == NULL)
    return;
    if(printed_level < level)
    {
    res.push_back(root->val);
    printed_level += 1;
    }
    helper(root->right, res, level+1, printed_level);
    helper(root->left, res, level+1, printed_level);
    }
    vector<int> rightSideView(TreeNode* root) {
    vector<int> result;
    if(!root) return result;
    int printed_level = -1;
    helper(root, result, 0, printed_level);
    return result;
    }


Log in to reply
 

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