Beats 100.00% using c++ without recursive method
IntuitionTo perform a preorder traversal (root → left → right), we need to process the root node first, followed by the left and right subtrees. A stack can be
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To perform a preorder traversal (root → left → right), we need to process the root node first, followed by the left and right subtrees. A stack can be used to simulate the recursive nature of the traversal, ensuring that nodes are processed in the correct order.

# Approach
<!-- Describe your approach to solving the problem. -->
1.Use a stack to simulate recursion.
2.Initialize the stack with the root node.
3.While the stack is not empty:
    Pop the top node and add its value to the result.
    Push the right child first (if it exists) so that the left child  is processed first when popped from the stack.
4.Return the result vector after all nodes are processed.

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n): Each node is visited exactly once, where 𝑛 is the total number of nodes in the tree.

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(h): The maximum size of the stack is determined by the height ℎ of the tree. In the worst case (a skewed tree), this could be 𝑂(𝑛).

# Code
```cpp []
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result; // Vector to store the preorder traversal
        if(root == NULL)
        {
            return result;
        }
        stack<TreeNode*> st; // Stack to manage traversal
        st.push(root); // Push the root node onto the stack

        while(!st.empty())
        {
            TreeNode* current = st.top();  // Get the node at the top of the stack
            st.pop(); // Remove it from the stack
            result.push_back(current->val); // Add the node's value to the result
        //will first insert right node so at the time of insertion the left will pop out
            if(current->right) 
            {
                st.push(current->right);
            }
            if(current->left)
            {
                st.push(current->left);
            }
        }
        return result;
    }
};
```
['C++']