C++ Non-recursive Solution using stack WITH explanation


  • 0
    U

    Basic idea:

    • put series of the left children of root into the stack
    • pop and print
    • put the (possible) right child and series of its left children into the stack
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            stack<TreeNode*> s;
            vector<int> ans;
            if (!root) return ans;
            while(root) {
                s.push(root);
                root = root->left;
            }
            while (!s.empty()) {
                TreeNode* tmp = s.top();
                s.pop();
                ans.push_back(tmp->val);
                if (tmp->right) {
                    tmp = tmp->right;
                    while (tmp) {
                        s.push(tmp);
                        tmp = tmp->left;
                    }
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.