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

  void dfs(TreeNode* root, vector<int>& res) {
    if (!root) {
      return;
    }
    res.emplace_back(root->val);
    dfs(root->left, res);
    dfs(root->right, res);
  }
};
class Solution {
 public:
  vector<int> preorderTraversal(TreeNode* root) {
    vector<int> res;
    stack<TreeNode*> s;
    TreeNode* t = root;
    while (t || !empty(s)) {
      while (t) {
        res.emplace_back(t->val);
        s.emplace(t);
        t = t->left;
      }
      t = s.top();
      s.pop();
      t = t->right;
    }
    return res;
  }
};
class Solution {
 public:
  vector<int> preorderTraversal(TreeNode* root) {
    vector<int> res;
    while (root) {
      if (!root->left) {  // 无左子树则右移
        res.emplace_back(root->val);
        root = root->right;
      } else {  // 有左子树,先获取左子树的最右节点
        TreeNode* t = getLeftMostRight(root);
        if (t->right == root) {  // 最右节点的下一节点如果指向根节点,则断开链接
          t->right = nullptr;
          root = root->right;
        } else {  // 最右节点的下一节点未指向根节点
          res.emplace_back(root->val);
          t->right = root;
          root = root->left;
        }
      }
    }
    return res;
  }

  TreeNode* getLeftMostRight(TreeNode* root) {
    TreeNode* t = root->left;
    while (t && t->right && t->right != root) {
      t = t->right;
    }
    return t;
  }
};