LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  vector<int> postorderTraversal(TreeNode* root) {
    vector<int> res;
    dfs(root, res);
    return res;
  }

  void dfs(TreeNode* root, vector<int>& res) {
    if (!root) {
      return;
    }
    dfs(root->left, res);
    dfs(root->right, res);
    res.emplace_back(root->val);
  }
};
class Solution {
 public:
  vector<int> postorderTraversal(TreeNode* root) {
    vector<int> res;
    stack<TreeNode*> s;
    TreeNode* t = root;
    TreeNode* last = root;
    while (t || !empty(s)) {
      while (t) {
        s.emplace(t);
        t = t->left;
      }
      t = s.top();
      if (!t->right || t->right == last) {
        s.pop();
        res.emplace_back(t->val);
        last = t;
        t = nullptr;
      } else {
        t = t->right;
      }
    }
    return res;
  }
};