3 different C++ solution


  • 1
    W
        void preorder(TreeNode* root, vector<int>& res) {
          if (root) {
            res.push_back(root->val);
            preorder(root->left, res);
            preorder(root->right, res);
          }    
        }
        vector<int> preorderTraversal(TreeNode* root) {
          vector<int> res;
          preorder(root, res);
          return res;
        } 
    
    vector<int> preorderTraversal(TreeNode* root) {
      vector<int> res;
      if (!root) return res;
      stack<TreeNode*> s;
      s.push(root);
      while (!s.empty()) {
        TreeNode* visit = s.top();
        s.pop();
        res.push_back(visit->val);
        if (visit->right)  s.push(visit->right);
        if (visit->left)  s.push(visit->left);
      }
      return res;    
    } 
    
    vector<int> preorderTraversal(TreeNode* root) {
      vector<int> res;
      stack<TreeNode*> s;
      TreeNode* p = root;
      while (p || !s.empty()) {
        while (p) {
          s.push(p);
          res.push_back(p->val);
          p = p->left;
        }
        if (!s.empty()) {
          p = s.top();
          s.pop();
          p = p->right;
        }
      }
      return res;
    }    
    

    ···


Log in to reply
 

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