Fastest C++ Code


#1

/**

  • Definition for binary tree

  • struct TreeNode {

  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    vector Solution::preorderTraversal(TreeNode
    A)
    {
    TreeNode* ptr=A;
    vectorV;
    if(ptr==NULL)
    {
    return V ;
    }

    stack<TreeNode* >S;
    S.push(ptr);

    while(!S.empty())
    {
    ptr=S.top();

     V.push_back(ptr->val);
     S.pop();
     
     if(ptr->right!=NULL)
     {
         S.push(ptr->right);
     }
    
     if(ptr->left!=NULL)
     {
         S.push(ptr->left);
     }
    

    }

    return V;
    }