Iterative Preorder Traversal

PHOTO EMBED

Sat Jul 29 2023 05:02:39 GMT+0000 (Coordinated Universal Time)

Saved by @simranjatav917 #c++

#include <vector>
#include <stack>

using namespace std;

// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> preorder;

        if (root == nullptr)
            return preorder;

        stack<TreeNode*> st;
        st.push(root);

        while (!st.empty()) {
            root = st.top();
            st.pop();
            preorder.push_back(root->val);

            if (root->right != nullptr) {
                st.push(root->right);
            }

            if (root->left != nullptr) {
                st.push(root->left);
            }
        }

        return preorder;
    }
};
content_copyCOPY