Accepted but I add a "private", is that OK?


  • 0
    Z
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            if(root)
            {
                result.push_back(root->val);
                preorderTraversal(root->left);
                preorderTraversal(root->right);
            }
            return result;
            
        }
    private:
        vector<int> result;
    };

  • 1
    S

    I believe to most interviewers, using a private variable should be fine, and it at least shows that you care about 'encapsulation', which is a good thing. However, what is not 'so fine' is: Your interviewer already points out that the recursive solution is trivial and asks you whether you can do it iteratively, but you still give the recursive solution. So please try to come up with a way to do it iteratively!


Log in to reply
 

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