Non-Recursive Soultion in C++


#1

vector Solution::preorderTraversal( TreeNode* A ) {

stack< TreeNode* > stk;
vector <int> ans;

if( A == NULL )
    return ans;

stk.push( A );

while( !stk.empty() ){
    
    TreeNode* svar = stk.top();
    
    stk.pop();
    
    ans.push_back( svar->val );
    
    if( svar->right != NULL )
        stk.push( svar->right );
        
    if( svar->left != NULL )
        stk.push( svar->left );
}

return ans;

}