DEV Community

Miss Pooja Anilkumar Patel
Miss Pooja Anilkumar Patel

Posted on • Updated on

589. Leetcode solution in Cpp

class Solution {
 public:
  vector<int> preorder(Node* root) {
    if (!root)
      return {};

    vector<int> ans;
    stack<Node*> stack{{root}};

    while (!stack.empty()) {
      root = stack.top(), stack.pop();
      ans.push_back(root->val);
      for (auto it = rbegin(root->children); it != rend(root->children); ++it)
        stack.push(*it);
    }

    return ans;
  }
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)