Share my iterative C++ solution 0ms


  • 2
    B
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            unordered_set<TreeNode*> myNode;
            vector<int> solution;
            stack<TreeNode*> mystack;
            if(root) mystack.push(root);
            while(!mystack.empty()){
                TreeNode* curNode=mystack.top();
                if (myNode.count(curNode)==0){
                    mystack.pop();
                    if(curNode->right)
                        mystack.push(curNode->right);
                    mystack.push(curNode);
                    if(curNode->left)
                        mystack.push(curNode->left);
                    myNode.insert(curNode);
                }
                else{
                    mystack.pop();
                    solution.push_back(curNode->val);
                }
            }
            return solution;
        }
    };

Log in to reply
 

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