My simple c++ 2 solutions


  • 3
    K
    class Solution {
    public:
    
    void helper(TreeNode * root, vector<int>& res)
    {
        if(!root)return;
        res.push_back(root->val);
        helper(root->left, res);
        helper(root->right, res);
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int>res;
        if(!root)return res;
        helper(root, res);
        return res;
    }
    

    };

    class Solution{
    public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int>res;
        stack<TreeNode*>stack;
        if(!root)return res;
        TreeNode * cur;
        
        stack.push(root);
        while(!stack.empty())
        {
            cur=stack.top();
            res.push_back(cur->val);
            stack.pop();
            if(cur->right)stack.push(cur->right);
            if(cur->left)stack.push(cur->left);
        }
        return res;
    }
    

    };


Log in to reply
 

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