Iterative Preorder Travesal using Stack
Intuition\nIterative Preorder Travesal using Stack\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\nO(n)\n\n
# Intuition\nIterative Preorder Travesal using Stack\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> preorderTraversal(TreeNode* root) {\n        vector<int> preorder;\n        if(root==NULL){\n            return preorder;\n        }\n        stack<TreeNode*> st;\n        st.push(root);\n        while(!st.empty()){\n            root=st.top();\n            st.pop();\n            preorder.push_back(root->val);\n\n            if(root->right!=NULL){\n                st.push(root->right);\n            }\n            if(root->left!=NULL){\n                st.push(root->left);\n            }\n        }\n        return preorder;\n    }\n};\n\n```
['C++']