Extremely easy and intuitive solution


#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) {
    stack <TreeNode*> st;
    vector ans;
    TreeNode *cur = A;
    while(cur!=NULL || st.empty()==false){
    if(cur==NULL){
    cur = st.top();
    st.pop();
    cur = cur->right;
    continue;
    }
    st.push(cur);
    ans.push_back(cur->val);
    cur = cur->left;

    }
    return ans;
    }