Simple iterative C++ solution using stack


#1

vector Solution::preorderTraversal(TreeNode* A) {

vector<int> ans;
stack<TreeNode *> s;
while(true){
    
    while(A != NULL){
        
        ans.push_back(A->val);
        s.push(A);
        A = A->left;    
    }
    
    
    if(s.empty()){
        break;
    }
    
    A = s.top();
    s.pop();
    A = A->right;
    
}
return ans;

}