Skip to content

Latest commit

 

History

History
47 lines (43 loc) · 764 Bytes

File metadata and controls

47 lines (43 loc) · 764 Bytes
  • 递归解法
class Solution {
 public:
  vector<int> preorder(Node* root) {
    vector<int> res;
    dfs(root, res);
    return res;
  }

  void dfs(Node* root, vector<int>& res) {
    if (!root) {
      return;
    }
    res.emplace_back(root->val);
    for (auto& x : root->children) {
      dfs(x, res);
    }
  }
};
  • 非递归解法
class Solution {
 public:
  vector<int> preorder(Node* root) {
    vector<int> res;
    if (!root) {
      return res;
    }
    stack<Node*> s;
    s.emplace(root);
    while (!empty(s)) {
      Node* t = s.top();
      res.emplace_back(t->val);
      s.pop();
      for (auto it = rbegin(t->children); it != rend(t->children); ++it) {
        s.emplace(*it);
      }
    }
    return res;
  }
};