C++ Iterative solution WITHOUT A STACK!


  • 0
    G
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            vector<int> result;
            
            while(root){
                auto left = root->left;
                
                if(!left){
                    result.push_back(root->val);
                    root = root->right;
                }
                else{
                  auto right = left;
                
                  while(right->right != nullptr && right->right != root){
                      right = right->right;
                  }
                
                  if(right->right == nullptr){
                      right->right = root;
                      root = left;
                  }
                  else{
                      right->right = nullptr;
                      result.push_back(root->val);
                      root = root->right;
                  }
                }
            }
            
            return result;
        }
    };
    

Log in to reply
 

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