Accepted code. Explaination with Algo.
Create an empty stack, Push root node to the stack.\n 2. Do following while stack is not empty.\n\n 2.1. pop an item from the stack and print it.\n \n 2.2. push
 1. Create an empty stack, Push root node to the stack.\n 2. Do following while stack is not empty.\n\n 2.1. pop an item from the stack and print it.\n \n 2.2. push the right child of popped item to stack.\n\n 2.3. push the left child of popped item to stack.\n\n \n\n\n>     class Solution {\n>     public:\n>         vector<int> preorderTraversal(TreeNode *root) {\n>             stack<TreeNode*> nodeStack;\n>             vector<int> result;\n>             //base case\n>             if(root==NULL)\n>             return result;\n>             nodeStack.push(root);\n>             while(!nodeStack.empty())\n>             {\n>                 TreeNode* node= nodeStack.top();\n>                 result.push_back(node->val);\n>                 nodeStack.pop();\n>                 if(node->right)\n>                 nodeStack.push(node->right);\n>                 if(node->left)\n>                 nodeStack.push(node->left);\n>             }\n>             return result;\n>             \n>         }\n>     };
[]