iterative Inorder Traversal in Binary Tree

PHOTO EMBED

Sat Jul 29 2023 06:08:08 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> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> inorder;

        TreeNode* node = root;

        while (true) {
            if (node != nullptr) {
                st.push(node);
                node = node->left;
            } else {
                if (st.empty())
                    break;

                node = st.top();
                st.pop();
                inorder.push_back(node->val);

                node = node->right;
            }
        }

        return inorder;
    }
};
content_copyCOPY