Elegant C++ iterative solution, 0ms, 10 lines


  • 6
    X
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            auto p = q.top();
            q.pop();
            if(p == NULL)
            {
                continue;
            }
            result.push_back(p->val);
            q.push(p->right);
            q.push(p->left);
        }
        
        return result;
    }

Log in to reply
 

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