Iterative solution in C++


  • 0
    W
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            TreeNode* p = root;
            std::stack<TreeNode*, std::vector<TreeNode*>> s;
            std::vector<int> result;
            while (p != nullptr || !s.empty()) {
                if (p != nullptr) {
                    do {
                        s.push(p);
                        p = p->left;
                    } while (p != nullptr);
                } else {
                    p = s.top();
                    s.pop();
                    result.push_back(p->val);
                    p = p->right;
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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