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> postorder(Node* root) {
    vector<int> res;
    dfs(root, res);
    return res;
  }

  void dfs(Node* root, vector<int>& res) {
    if (!root) {
      return;
    }
    for (auto& x : root->children) {
      dfs(x, res);
    }
    res.emplace_back(root->val);
  }
};
class Solution {
 public:
  vector<int> postorder(Node* root) {
    vector<int> res;
    if (!root) {
      return res;
    }
    stack<pair<Node*, int>> s;  // 记录已添加的子节点数
    s.emplace(root, 0);
    while (!empty(s)) {
      auto& [t, i] = s.top();
      if (i == size(t->children)) {
        res.emplace_back(t->val);
        s.pop();
      } else {
        s.emplace(t->children[i++], 0);
      }
    }
    return res;
  }
};